将数字字符串转换为数字(仅限f浮点数)my_atof()

来源:互联网 发布:淘宝怎么优化标题 编辑:程序博客网 时间:2024/05/07 22:35
编写一个函数,将一个数字字符串转换成该字符串对应的数字(包括正整数、负整数)

例如:“    1.234“   返回1.234

             " 1.234“   返回1.234

          “ -1.234“ 返回-1.234

函数原型:double  char_int(char *str){}


#include <stdio.h>#include <math.h>#include <ctype.h>double my_atof(char *str)//atof()在math.h中,自己实现的my_atof(){int flag = 1;double value = 0;double num = 0;int count = 0;//判断空白字符while(isspace(*str)){str++;}//判断正负号if(*str == '-'){flag = -1;str++;}if(*str == '+'){str++;}while(*str != '\0'){if(*str == '.'){count++;str++;continue;}if(count){count *=10;}value = value * 10 + (*str -'0');str++;}value = value / count;return flag * (value);}int main(){char *p = "-12.34";printf("%f\n",my_atof(p));}


0 0