将string转float
01 /*
02 * C/C++中一次遍历将string转float (带小数点)
03 * Written by Jesse
04 */
05
06 #include <math.h>
07
08 double str2float(char *str)
09 {
10 int i = 0;
11 int intpart, floatpart, digit;
12 int sign = 1;
13 int power = -1;
14 int beforepoint = 1;
15 double result;
16
17 if(str[i] == '-')
18 {
19 i++;
20 sign = -1;
21 intpart = str[i] - '0';
22 i++;
23 }
24 else
25 {
26 intpart = str[i] - '0';
27 i++;
28 }
29
30 for(; str[i] != '\0'; i++)
31 {
32 if(str[i] == '.')
33 {
34 beforepoint = 0;
35 floatpart = str[++i] - '0';
36 continue;
37 }
38
39 if(beforepoint)
40 {
41 digit = str[i] - '0';
42 intpart = intpart*10 + digit;
43 }
44 else
45 {
46 power--;
47 digit = str[i] - '0';
48 floatpart = floatpart*10 + digit;
49 }
50 }
51 result = sign * (intpart + floatpart * pow(10, power));
52
53 return(result);
54 }