开发者

C: Any way to convert text string to float, i.e. 1e100?

Unfortunately开发者_StackOverflow中文版 in this log I have there are some strings with that notation (1.00e4), I know I can use printf with the "%e" specifier to create that notation, how would I read it?

Unfortunately strtof and scanf seem to return 0.00000 on "1e100", would I need to write my own parser for this?

(updated)

What I have as input:

string "4.1234567e5", or "4.5e5"

Desired output:

float 412345.67, or integer "450000"


You can use also

double atof( const char * str );


Start with this code:

#include <stdio.h>
int main (void) {
    double val;
    double val2 = 1e100;
    sscanf ("1e100", "%lf", &val);  // that's an letter ELL, not a number WUN !
    printf ("%lf\n", val);          // so is that.
    printf ("%lf\n", val2);         // and that.
    return 0;
}

It outputs:

10000000000000000159028911097599180468360810000000000...
10000000000000000159028911097599180468360810000000000...

The reason it's not exactly 1100 is because of the nature of IEEE754 floating point values. Changing it to:

#include <stdio.h>

int main (int argc, char *argv[]) {
    double val;
    int i;
    for (i = 1; i < argc; i++) {
        sscanf (argv[i], "%lf", &val);
        printf ("   '%s' -> %e\n", argv[i], val);
    }
    return 0;
}

and running it with your sample arguments gives:

pax$ ./qq 4.1234567e5 4.5e5 3.47e10 3.47e-10
   '4.1234567e5' -> 4.123457e+05
   '4.5e5' -> 4.500000e+05
   '3.47e10' -> 3.470000e+10
   '3.47e-10' -> 3.470000e-10


It doesn't work if I use float data type. Perhaps the problem lies there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜