-3

With working with floating point values I don't know why my C compiler or the System is behaving unexpectedly. Not making it so confusing. Here is a simple program to take float value input and print the same.

#include <stdio.h>

int main()
{
    float num;

    printf("Enter float value ");
    scanf("%f", &num);

    printf("Value = %f", num);

    return 0;
}

On multiple run of the same code giving me different and weird outputs. Here are some sample runs.

Sample Run #1 Correct Output

Enter float value 12.0312
Value = 12.031200

Sample Run #2 Incorrect and unexpected output

Enter float value 324.123
Value = 324.122986

Sample Run #3 Incorrect and unexpected output

Enter float value 945.1234
Value = 945.123413

I don't know why the system is adding some garbage values at the end. I am using GNU GCC compiler in code::blocks.

Pankaj Prakash
  • 2,300
  • 30
  • 31
  • 3
    The system is not "adding garbage values". Floating-point representations are inherently imprecise (they don't represent real numbers, they represent a subset of rational numbers.) – The Paramagnetic Croissant Aug 26 '15 at 15:48
  • http://floating-point-gui.de/ – pm100 Aug 26 '15 at 15:49
  • Thanks everyone for making it clear. And for the link. Here is what I found the correct answer to my question http://stackoverflow.com/questions/588004/is-floating-point-math-broken. If in case anyone else has this question this link can help. – Pankaj Prakash Aug 26 '15 at 15:58

2 Answers2

3

Your float cannot represent every conceivable number exactly. It has limitations. The closest float to "324.123" is 324.122986...

If you need more precision, use double, but even that has its limits too.

A float will be correct (match similarly limited input) to at least FLT_DIG significant digits. To print a number to FLT_DIG significant digits use:

printf("%.*e", FLT_DIG - 1, num);

FLT_DIG is at least 6.

number of decimal digits, q, such that any floating-point number with q decimal digits can be rounded into a floating-point number with p radix b digits and back again without change to the q decimal digits, ... C11dr §5.2.4.2.2 11

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0
printf("Value = %f", num);

It will add some value if like : Enter float value 945.1234 Value = 945.123413

because float value always print a 6 digit after the decimal point

to avoid this you can use the statement like : printf("Value = %.3f", num);

This Will Give You A desire output as you want it will print only three number after the decimal point you can set as per your requirement like "%.2f" ->for 2 number after the decimal "%.3f" ->for 3 number after the decimal "%.4f" ->for 4 number after the decimal

ALI SHEKH
  • 15
  • 1
  • 8