开发者

ansi-c fscanf problem

hi i read the file as follows

       fscanf(fp,"%f %f %f\n",&*(p1+i), &*(p2+i), &*(p3+i));

my file's lines consists of three floating point numbers...

the problem i have is that in the file let's say i have some floating points with let's say maximum of two digits after the dot. but when i ask c to print those values using different formatting, for example %lf,%.2lf,%.4lf... it starts to play w开发者_StackOverflowith the digits... my only concern is this, if i have let's say 1343.23 in the file, then will c use this value exactly as it is in computations or it will play with the digits after the dot. if it will play, then how is it possible to make it so that it uses floating point numbers exactly as they are? for example in last case even if i ask it to print that value using %.10lf i would expect it to print only 1343.2300000000.? thanks a lot!


The "problem" is that floating point numbers are by definition, approximate. You should read What Every Computer Scientist Should Know About Floating-Point Arithmetic for more information.

Also, you can simplify &*(x) to x, so you should write p1+i, p2+i, p3+i in your fscanf call.


When you read in the string 1343.23, considering it to be a decimal number, it is converted to the computer's internal binary representation. Outputting with a format specifier converts from binary to decimal. On output, if you ask for a different number of digits after the decimal point, you may not get exactly the same value. A particular floating point decimal number may not be exactly representable in a finite-length binary floating point number, so rounding should be expected.

For a better explanation, see the famous article What Every Scientist Should Know About Floating-Point Arithmetic.


The number of digits after the dot does not make any difference to fscanf. You should get rid of the &* thing and add a new line to the end of the string:

fscanf(fp, "%f %f %f\n", p1 + i, p2 + i, p3 + i);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜