字符串转浮点数

直接上代码:

#include<stdio.h>
double my_atof(char *str)
{
	char *p = NULL;
	double result1 = 0, result2 = 0, result = 0;
	int flag = 0;
	double temp = 10;
	p = str;
	if(NULL == str)
		return -1;
		
	if('-' == *p) {
		flag = 1;
		p++;
	}
	
	while(p != NULL && (*p<= '9' && *p >= '0'))
	{
	
		result1 = result1 * 10 + (*p -48);
		p++;
	}
	if('.' == *p)
	{
		p++;
		while(p != NULL && (*p<= '9' && *p >= '0'))
		{
			result2 = result2 + (double)(*p -48)/temp;;
			temp = temp * 10;
			p++;
		}
	}
		result = result1 + result2;
		
	if(1 == flag)result = -result;
	
	return result;
}

void main()
{
	char szString[] = "-012345678999.0123456789";
	double db2 = 1123456789123456789.0;
	int i = 1;
	double db3, db4 = 0.123456;
	db3 = db2 + db4;
	printf(" db3 = %f\n",db3);
	//printf("%c \n", szString[3]);
	db2 = my_atof(szString);
		printf("/nsscanf result:\n");
    printf("%f  %.12f  %.2f  %e  %E\n", db2, db2, db2, db2, db2);
}

注意如果 浮点数 '.' 号前面的数字很大,两个数相加会出现问题,暂时没有找到解决 方法

另外是直接调用标准接口,见:

http://blog.csdn.net/loomman/article/details/3373298


你可能感兴趣的:(字符串转浮点数)