0
#include<stdio.h>

int main(){

    float x =5400.768;

    printf("%f", x);

}

In the above code, once I execute the program it will display 5400.768066 as output with 3 extra decimal places. Why is that?

Leo Adberg
  • 342
  • 2
  • 18
anjana_dodampe
  • 121
  • 1
  • 1
  • 6
  • This is because of the way floating point numbers are stored in memory. Unlike integers, floats are not precisely stored in memory; instead an exponent and mantissa is stored. http://kipirvine.com/asm/workbook/floating_tut.htm – Gillespie Mar 17 '19 at 03:43
  • @AiSER_HD, adding 4 spaces in front of your code will make it display as code – J'e Mar 17 '19 at 03:47

2 Answers2

0

The problem is floating point inaccuracy. Basically, the number is stored in 32 bits, which can only contain a finite amount of precision, and usually only have ~7 decimal digits of precision. If you need more accuracy you could use a 64-bit value (aka double).

Leo Adberg
  • 342
  • 2
  • 18
0

Have a look at this https://m.youtube.com/watch?v=f4ekifyijIg if you wanna know how floats are stored in memory.

If you want to print just to 3 decimal places, use printf("%.3f",variable_name);.

Saurabh
  • 43
  • 1
  • 15