自己实现的字符串转换浮点数的代码
模电期中考试无聊写的- -
先记录一下, 以后有时间在优化。
精度之类的等等问题也暂时没有考虑
// =====================================================================================
//
// Filename: my_atoi.c
//
// Description:
//
// Version: 1.0
// Created: 2014年11月14日 19时19分48秒
// Revision: none
// Compiler: g++
//
// Author: wangweihao (wangweihao), 578867817@qq.com
// Company: none
//
// =====================================================================================
/*
* 实现字符转转浮点函数
* 浮点数可能有普通浮点数和科学计数法的浮点数
* 情况比较多
* 举个例子
* 3.14 0.314 314 3.14e10(等价于3.14e+10) 3.14e-10
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
double my_atoi(char *s)
{
int i, length, newlength;
int flag = 0, flag2 = 0; //标记'.' , 和'e'
int flagIndex = 0, flagIndex2 = 0;
char symbol;
double sum = 0; //计算最后的总和
double sum1 = 0, sum2 = 0, sum3 = 0;
double ten1 = 1, ten2 = 0.1, ten3 = 1;
length = strlen(s);
for(i = 0; i < length; ++i)
{
if(isdigit(s[i]))
;
else if(ispunct(s[i]))
{
if(s[i] == '.')
{
flagIndex = i;
++flag;
}
}
else if(isalpha(s[i]))
{
if(s[i] == 'e')
{
++flag2;
flagIndex2 = i;
}
if(i < length)
{
symbol = s[i+1]; //存储符号
}
}
}
if(flag > 1 || flag2 > 1)
{
printf("error input\n");
exit(-1);
}
//printf("flag = %d, flagIndex = %d, flag2 = %d, flagIndex2 = %d\nsymbol = %c\n", flag, flagIndex, flag2, flagIndex2, symbol);
if(flag2 != 0)
length = flagIndex2;
if(flag == 0 && flag2 == 0)
{
for(i = length-1; i >= 0; --i)
{
sum += (s[i]-48)*ten1;
ten1 *= 10;
}
return sum;
}
for(i = flagIndex-1; i >= 0; --i)
{
sum1 += (s[i]-48)*ten1;
ten1 *= 10;
}
for(i = flagIndex+1; i < length; ++i)
{
sum2 += (s[i]-48)*ten2;
ten2 /= 10;
}
length = strlen(s);
for(i = length-1; isdigit(s[i]); --i)
{
sum3 += (s[i]-48)*ten3;
ten3 *= 10;
}
if(flag2 != 0)
{
if(symbol == '-')
{
sum3 = -sum3;
sum = (sum1 + sum2)* (pow(10, sum3));
return sum;
}
else
sum = (sum1 + sum2)* (pow(10, sum3));
return sum;
}
sum = sum1 + sum2;
return sum;
}
int main(int argc, char *argv[])
{
char *p1 = "3.14";
char *p2 = "0.314";
char *p3 = "314";
char *p4 = "3.14e3";
char *p5 = "3.14e+3";
char *p6 = "3.14e-3";
char a[100];
printf("p1:%lf, p2:%lf, p3:%lf, p4:%lf, p5:%lf, p6:%lf\n", my_atoi(p1), my_atoi(p2), my_atoi(p3), my_atoi(p4), my_atoi(p5), my_atoi(p6));
scanf("%s", a);
printf("my_atio(%s): %lf\n", a, my_atoi(a));
return 0;