1

I have 2 doubles x and y. When I divide x/y I dont get the result I am hoping to get.

Here is the printf command I am using in c and the output I am getting:

command:

printf("%3.10f %3.2f %3.12f %d\n",x,y,x/y,(int)(x/y));

output:

1.0000000000 0.10 10.000000000000 9

To me, x/y ought to be 10 and so not sure why (int)(x/y) is producing 9 instead of 10.

Can someone help me understand this surce of this problem please?

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
Dinesh Subedi
  • 2,603
  • 1
  • 26
  • 36
  • Duplicate of http://stackoverflow.com/questions/3587442/casting-int-as-float – Polynomial Nov 07 '11 at 16:20
  • [This](http://stackoverflow.com/questions/6722293/why-comparing-double-and-float-leads-to-unexpected-result/6722297#6722297) should be a good read. – Alok Save Nov 07 '11 at 16:25
  • 1
    @Polynominal: Not a dupe. That question is casting an int to float. This question here is casting the other way around. – DevSolar Nov 07 '11 at 16:25

3 Answers3

4

x/y results in slightly less than 10 (it surely is less than 10^-12 off, otherwise the other result wouldn't show as 10.000000000000), probably due to the usual floating point math rounding errors.

The printf performs rounding to the digit of the requested precision, but the conversion to int is a brutal truncation, thus, even if it's 9.99999999999999... you get 9 as a result.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
3

This happens because you are truncating the decimal part. Round it, and you should be fine.

printf("%3.10f %3.2f %3.12f %d\n",x,y,x/y,round(x/y));
Rok Kralj
  • 46,826
  • 10
  • 71
  • 80
1

casting to int doesn't round a double to the nearest integer.

Look at round() for float in C++ for details

Community
  • 1
  • 1
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85