-
converting double to int
Hi everyone...
I was wondering if there is a way to convert a double value to an int value.
What i'm trying to do is to find the ceiling of an integer divided by 2.
Code:
#include<math.h>
int num = 5;
double value = ceil(5/2);
//int ceiling = value ///I want to do this.....
Thank you!!
-
That's legal in C++. The compiler probably issues a warning, which you can get rid of by making the cast explicit.
int ceiling = (int) value;
-
But beard in mind that 4.99999 will yield 4 in this situation. There's no rounding - just cutting off the decimal portion.
-
You could add .5 to the double named value and use floor() to round off, or subtract .5 and use ceil().
4.9 + .5 = 5.4, which will floor() to 5.0
Even if you ceil() or floor() a double, it's not an int; the value is 2.0, or 3.0, or whatever, not 2 or 3. Use the cast like SilentStrike said.
-
look in the function list at cprogramming theres one to round it off then turn it into an int