dykw dykw - 2 months ago 32
C Question

Read double using fscanf

I want to read double from text file
e.g.
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!

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

yzt yzt
Answer

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.