0

I have problem with scanf function in C.

I want read double value 0.01 from keyboard (in console application) but when i try to print this value on screen it returns 0.01000000000000000021 and i have no idea why. I need exact 0.010000000000000

My sample test code looks like this:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char** argv) {
    double value;

    printf("Write double value:\n");
    scanf("%lf", &value);

    printf("%.20f", value);
    return(EXIT_SUCCESS);
}

Can someone help me?

user1827257
  • 1,600
  • 4
  • 17
  • 24
  • 1
    You will not get exact fractions of 10, except say `5/10`. Bear in mind that a 64-bit variable can only store `2**64` different values. Extend the *range* from the basic `int` and you cannot store all possible values within that range. – Weather Vane Oct 29 '16 at 17:08
  • First, floating point values don't have infinite precision. When converting text, libraries attempt to pick the floating point number that's closest to the value represented by the string. In your case, the digits "21" lie outside the precision of doubles, which is 53 bits - about 16 decimal digits. They're meaningless. If you print 16 significant digits, you'll get what you want. – Gene Oct 29 '16 at 17:11
  • 1
    There is an infinite number of floating point values within the specified range of `double`, which can only represent 2**64 of them. The others are rounded to the nearest exact representation. – Weather Vane Oct 29 '16 at 17:52

0 Answers0