2

I'm trying to read a float value from the keyboard input using scanf.

float n; printf("Input a float value: "); scanf("%f", &n);

When I input 4.2, the value of my variable turns to be 4,19999981. screenshot

I need to devide the inputed value by another float value, so I get unrelevant result. I can't limit the number of signs after the comma, cause I don't know how many figures a user wants to input. How to solve the problem?

Iren
  • 43
  • 4
  • 1
    There's only so many bits to represent decimal numbers, it's impossible to exactly represent every value, so a best approximation is done. If you want more precision you can use a `double` (more bits), but the same core problem remains. See an in-depth explanation here: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – yano Mar 30 '18 at 16:16
  • yano, is there any way to multiply the inputed float value by 100 and then recognize it as an int? It would help me – Iren Mar 30 '18 at 16:53
  • sure.. `int myInt = (int)(n * 100.0f);` This will multiply by 100, convert to an `int`, and _truncate_ any decimal value (it will not round). But if you want an `int`, just use `scanf` to get an `int`. Note that in most cases you want to avoid using `float`s and `double`s because of these precision errors. You should only use them if you are _sure_ rounding and approximations are ok. – yano Mar 30 '18 at 17:00
  • 1
    @yano, Code could round values `long myInt = lrint(n * 100.0);` to avoid truncation issues. – chux - Reinstate Monica Mar 30 '18 at 17:04
  • @chux thanks for the info, I was not aware of that function – yano Mar 30 '18 at 17:06
  • yano, chux, thank you very much! I've found another solution - to get a float value, multiply it by 100, and then round it to the nearest integer using the round() function, – Iren Mar 30 '18 at 17:11

0 Answers0