Read double using fscanf

后端 未结 2 1119
Happy的楠姐
Happy的楠姐 2021-01-14 09:35

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.9316

相关标签:
2条回答
  • 2021-01-14 10:31

    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.

    0 讨论(0)
  • 2021-01-14 10:32

    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.
    0 讨论(0)
提交回复
热议问题