C++ 使用 fscanf 读取 double
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17852269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read double using fscanf
提问by dykw
I want to read double from text file e.g. 31 39.9316476397222 116.113516352222
我想从文本文件中读取 double,例如 31 39.9316476397222 116.113516352222
I tried both, not work. I can only read the first few decimal digital e.g. 39.93164 but not 39.9316476397222 anyone knows why? Thanks!
我两个都试了,不行。我只能读取前几个十进制数字,例如 39.93164 但不能读取 39.9316476397222 有谁知道为什么?谢谢!
int NodeID;
double _lat,_long;
fscanf (pFile, "%d %lf %lf", &NodeID,&_lat,&_long);
printf ("I have read: %d %f %f\n", NodeID,_lat,_long);
fscanf (pFile, "%d %lf %lf", &NodeID,&_lat,&_long);
printf ("I have read: %d %lf %lf\n", NodeID,_lat,_long);
回答by toddwz
According to the fscanf man page, you should use %lffor double :
根据fscanf 手册页,您应该使用%lfdouble :
f, e, g (Floating point number) : A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod). Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.
f、e、g(浮点数):一系列十进制数字,可选包含小数点,可选前面有符号(+ 或 -),可选后跟 e 或 E 字符和十进制整数(或一些strtod 支持的其他序列)。符合 C99 的实现也支持以 0x 或 0X 开头的十六进制浮点格式。
回答by yzt
I think the numbers are read correctly. Your problem is in your printing out, which makes you think you don't have the whole number. Keep in mind that printftypically only outputs a few digits after the decimal point.
我认为这些数字是正确读取的。您的问题在于您的打印输出,这让您认为您没有完整的数字。请记住,printf通常只输出小数点后的几位数字。
I suggest you do these:
我建议你做这些:
- In your
printfcalls, use a format specifier like this: "%.20f". It tellsprintfto output 20 digits after the decimal point. - Keep in mind that whatever floating-point you use,
floatordoubleorlong double, it's going to have a limited precision and resolution. Familiarize yourself with floating-point numbers and how they work and are represented.
- 在您的
printf调用中,使用如下格式说明符:“%.20f”。它告诉printf输出小数点后的 20 位数字。 - 请记住,无论您使用浮点数
floatordouble或long double,它的精度和分辨率都是有限的。熟悉浮点数及其工作方式和表示方式。


