0

Answer comes wrong when using decimal places!

I'm running the following program:

#include<stdio.h>

#include<math.h>

main()

{

float x,y,div;

printf("Enter two numbers x,y \n");

scanf("%f%f",&x, &y);

div=x/y;

printf("div=%12.10f\n",div;

return 0;

}

After running, when I put x=1 and y=3 then answer comes 0.3333333433, but answer should be 0.3333333333. Why this error comes ? How can I get rid from this kind of error ? Please help.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Empty
  • 109
  • 2
  • 3
    Turbo C++? Which year is this? :) – Sourav Ghosh Sep 30 '20 at 15:12
  • `printf("%12.10f %a\n", div, div);` might help you understand what's going on. – zwol Sep 30 '20 at 15:18
  • You have run into the limits of 32-bit floating point precision. Only 6 significant digits are guaranteed to be accurate, so your best bet is to use `"%.6g"` for your format specifier. However, should you wish to round-trip the float, use `"%.9g"` (ie, such that scanf will return the same float). For double, the relevant numbers are 15 and 17. – taniwha Sep 30 '20 at 15:19
  • 2
    plese only tag what you actually use. It cannot be C and C++, and Turbo C++s support stopped before C++11 came out – 463035818_is_not_an_ai Sep 30 '20 at 15:20
  • Also see https://stackoverflow.com/questions/44863062/ for why Sourav is asking "what year is this?" – zwol Sep 30 '20 at 15:21
  • Required reading: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Thomas Matthews Sep 30 '20 at 16:07

1 Answers1

0

A float cannot represent every real number exactly, only about 232 of them. 1.0f/3.0f does not get saved as 0.3333333333, instead a nearby value is saved: 0.3333333432674407958984375 - a dyadic rational.

Printing that out to 10 decimal places after the . is 0.3333333433.

How can I get rid from this kind of error ?

Use higher precision types like double for this example. Still a like issue will occur with higher precision output "%22.20f".

... or instead change your expectations of using binary floating point to form decimal answers.

.... wait for a next version of C2X which may have decimal floating point.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Re “may have decimal floating point”: That’s not going to represent ⅓ exactly either. – Eric Postpischil Sep 30 '20 at 17:18
  • @EricPostpischil True, yet OP's goal was to print a rounded value - not exact. With common FP, two roundings occurred in OP's code (first one was binary in the quotient calculation), 2nd was in printing with a decimal rounding. With decimal FP, both roundings still occur and risk the usual issue about _double roduning_. Being both in decimal, the effect remains but to a lesser surprising extent. – chux - Reinstate Monica Sep 30 '20 at 17:25