Dinesh Subedi
Dinesh Subedi

Reputation: 2663

Having trouble with casting: (int)

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?

Upvotes: 1

Views: 176

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126777

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.

Upvotes: 4

Rok Kralj
Rok Kralj

Reputation: 48715

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));

Upvotes: 3

parapura rajkumar
parapura rajkumar

Reputation: 24403

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

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

Upvotes: 1

Related Questions