I know that C++ provides us with a ceil function. For practice, I was wondering how can we implement the ceil function in C++. The signature of the method is
public static int ceil(float num)
Please provide some insight.
I thought of a simple way: Convert num to a string, find the index of the decimal point, check if the decimal part is greater than 0. If yes, return num+1 else return num. But I want to avoid using the string conversion
Here is a naive implementation for positive numbers (this uses the fact that casting to
(int)truncates toward zero):It is easy to extend this to work with negative numbers too.
Your question asked for a function returning
int, but normally theceil()function returns the same type as its argument so there are no problems with the range (that is,float ceil(float num)). For example, the above function will fail ifnumis 1e20.