tags:

views:

287

answers:

4

I want to implement greatest integer function. [The "greatest integer function" is a quite standard name for what is also known as the floor function.]

int x = 5/3;

My question is with greater numbers could there be a loss of precision as 5/3 would produce a double?

EDIT: Greatest integer function is integer less than or equal to X. Example:

4.5 = 4
4 = 4
3.2 = 3
3 = 3

What I want to know is 5/3 going to produce a double? Because if so I will have loss of precision when converting to int.

Hope this makes sense.

+5  A: 

You will lose the fractional portion of the quotient. So yes, with greater numbers you will have more relative precision, such as compared with 5000/3000.

However, 5/3 will return an integer, not a double. To force it to divide as double, typecast the dividend as (double)5/3.

spoulson
Thanks all I needed to know.
Thomas
+1  A: 

5/3 will always produce 1 (an integer), if you do 5.0/3 or 5/3.0 the result will be a double.

Virgil
A: 

Since in C and C++, as others have said, / is integer division, it will return an int. in particular, it will return the floor of the double answer... (C and C++ always truncate) So, basically 5/3 is exactly what you want.

It may get a little weird in negatives as -5/3 => -2 which may or may not be what you want...

Brian Postow
But if you're clever, you can use negatives to implement integer `ceil()`...
Mike DeSimone
heh this is true.
Brian Postow
+1  A: 

Integer division gives integer results, so 5 / 3 is 1 and 5 % 3 is 2 (the remainder operator). However, this doesn't necessarily hold with negative numbers. In the original C++ standard, -5 / 3 could be either -1 (rounding towards zero) or -2 (the floor), but -1 was recommended. In the latest C++0B draft (which is almost certainly very close to the final standard), it is -1, so finding the floor with negative numbers is more involved.

David Thornley