简体   繁体   English

使用fscanf读取double

[英]Read double using fscanf

I want to read double from text file eg 31 39.9316476397222 116.113516352222 我想从文本文件中读取双倍,例如31 39.9316476397222 116.113516352222

I tried both, not work. 我尝试了两种,而不是工作。 I can only read the first few decimal digital eg 39.93164 but not 39.9316476397222 anyone knows why? 我只能读取前几个十进制数字例如39.93164而不是39.9316476397222谁知道为什么? Thanks! 谢谢!

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);

According to the fscanf man page , you should use %lf for double : 根据fscanf手册页 ,你应该使用%lf表示double:

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). f,e,g(浮点数):一系列十进制数字,可选地包含小数点,可选地前面带有符号(+或 - ),可选地后跟e或E字符和十进制整数(或者一些strtod支持的其他序列)。 Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X. 符合C99的实现在前面加上0x或0X时也支持十六进制浮点格式。
在此输入图像描述

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 printf typically only outputs a few digits after the decimal point. 请记住, printf通常只在小数点后输出几位数字。

I suggest you do these: 我建议你这样做:

  1. In your printf calls, use a format specifier like this: " %.20f ". printf调用中,使用如下格式说明符:“ %.20f ”。 It tells printf to output 20 digits after the decimal point. 它告诉printf在小数点后输出20位数。
  2. Keep in mind that whatever floating-point you use, float or double or long double , it's going to have a limited precision and resolution. 请记住,无论你使用什么浮点, floatdoublelong double ,它都将具有有限的精度和分辨率。 Familiarize yourself with floating-point numbers and how they work and are represented. 熟悉浮点数以及它们如何工作和表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM