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


 1 //写一个把字符串转换为浮点数的程序
 2 #include <ctype.h>
 3 #include <stdlib.h> //这个头文件里含有atof的标准库函数声明
4 double atof2(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-1616:48:07 BY PeaceCoder


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM