编写一个函数,将一个数字字符串转换成这个字符串对应的数字(包括正浮点数,负浮点数)

来源:互联网 发布:最好的房屋设计软件 编辑:程序博客网 时间:2024/05/20 00:15
eg:"12.34"返回12.34,“123.34”返回123.34,函数原型:double my_atof(char *str)
#include <stdio.h>  #include <ctype.h>  double my_atof(char *str)  {      int flag = 1;      int count = 1;      double num = 0;      double value = 0;      while(isspace(*str))      {          *str++;      }      if(*str == '-')      {          flag = -1;          *str++;      }      if(*str == '+')      {          *str++;      }      while(*str != '\0'&&*str != '.')      {          value = value * 10 + (*str - '0');          *str++;      }      *str++;      while(*str != '\0')      {          count *= 10;          num = num * 10 + (*str - '0');          *str++;      }      num = num/count;      return  flag * (value + num);  }  int main(void)  {      char *str1 = "12.34";      char *str2 = "-123.34";      printf("%f\n",my_atof(str1));      printf("%f\n",my_atof(str2));      return 0;  }  

0 0
原创粉丝点击