转化字符串为双精度浮点数(包括对科学计数法的处理)的函数atof

 1 //写一个把字符串转换为浮点数的程序
 2 #include <ctype.h>
 3 
 4 double atof(char s[]){
 5     double res; int i; int sign = 1;
 6     double fpart = 1.0;
 7     double exp = 10;
 8     int expNum = 1;
 9     double n = 1.0;
10     //读掉字符串前面可能有的空格
11     for (i = 0; isspace(s[i]); i++)
12         ;
13     //读取正负的标识
14     if (s[i] == '-'){
15         sign = -1;
16         i++;//把指针递增放在分支里,以免在判断不成功时向后移动
17     }
18     for(res = 0.0 ; isdigit(s[i]); i++){
19         res = res * 10.0 + ((int)s[i] - '0');
20     }
21     if (s[i++] == '.'){
22         for (fpart = 1.0; isdigit(s[i]); i++){
23             res = res * 10.0 + ((int)s[i] - '0');
24             fpart *= 10.0;
25         }
26     }
27     if (s[i++] == e){
28         if (s[i] == '-'){
29             exp = 0.1;
30             i++;
31         }
32         expNum = atoi((s + i))
33     while (expNum-- > 0){
34         n *= exp; 
35     }
36     }
37     res = res * sign / fpart * n;
38     return res;
39 }

2021-06-16 BY PeaceCoder

posted @ 2021-06-16 16:46  平心执剑  阅读(127)  评论(0)    收藏  举报