简体   繁体   中英

Read double using fscanf

I want to read double from text file eg 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? 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 :

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.
在此输入图像描述

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.

I suggest you do these:

  1. In your printf calls, use a format specifier like this: " %.20f ". It tells printf to output 20 digits after the decimal point.
  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. Familiarize yourself with floating-point numbers and how they work and are represented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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