Question

I have two variables:

size_t a = 63;
size_t b = 32;

I called the function ceil(a/b). Naturally I would assume that the answer returns 2 but instead it returns 1.

I'm puzzled. I have tried casting the variables to a double or int and it doesn't seem to help.

Thanks for any help.

Was it helpful?

Solution

Let's break down what happens when you do ceil(a/b). First, an integer division happens between a and b, so 63/32 becomes (int)1, and then this 1 is casted to double to become 1.0, and then ceil(1.0) is of course just 1.0.

If you expect to get 2, you need to convert to double before the division occurs, i.e. ceil(double(a) / double(b)) uses double division.

OTHER TIPS

The ceil and floor functions work on double types. You have done an integer division (because size_t is an integer type), so the result is an integer (ie it's already a whole number, so you cannot round up or down). Try casting to double before the division:

ceil( double(a) / double(b) );
floor( double(a) / double(b) );

You technically only need to cast the first one, because then you will get floating-point division instead. But it's good to be explicit and cast both.

Both 63 and 32 are ints, hence the result will be an int (i.e. 1 and not 1.96875).

Either typecast it as specified by paddy or

or use double values

ceil(63.0/32); // promotes 32 from int to double since one of the operand(63.0) is double.
ceil(63.0/32.0); // both operands are doubles

a/b will perform an integer division since they are integral types, which will result in 1, this explains why std::ceil returns the value you are seeing. if we look at the draft C++ standard section 5.6 Multiplicative operators paragraph 4 says(emphasis mine):

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded;[...]

casting either of the operands to double will be sufficient due to arithmetic conversions which are covered in section 5 Expressions paragraph 10 which says(emphasis mine):

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

and includes this bullet:

Otherwise, if either operand is double, the other shall be converted to double.

So the following expression will yield the result you desire:

std::ceil( double(a)/b)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top