Why a double variable in C doesn't like to store the number '7'?

Debojit Acharjee 455 Reputation points
2023-05-29T03:41:14.3733333+00:00

I tested a double variable in C to store the value '12345678901234567'. But it can't store the last digit '7' and shows it as '8'. However, if I change the last digit to '6' or '8', then it can show the same value. What is that?

Here is the program:

#include <stdio.h>

int main()

{

    double a;

   

    a = 12345678901234567;

    printf("%lf", a);

    return 0;

}

Output: 12345678901234568.000000

 

Developer technologies C++
Developer technologies C#
{count} votes

Accepted answer
  1. YujianYao-MSFT 4,296 Reputation points Microsoft External Staff
    2023-05-29T05:53:34.3933333+00:00

    Hi Debojit Acharjee,

    I tested your code and got the same results as you, but when I tried to output 12345678901234566 and 12345678901234568, my compiler was able to display them correctly. The compiler I'm using is VS2022, I suggest you try it.

    User's image

    User's image

    In C language, if you assign a number to a double variable, the compiler will do its best to represent it as a double. In some cases it may round to the nearest representable number, while in other cases it may choose a close representable number.

    This behavior depends on the specification and implementation details of floating-point numbers, as well as compiler and hardware differences. Therefore, even the same code may give different results when run on different compilers or platforms.

    Best regards,

    Elya Yao


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.