I feel really silly asking this because I know how to do it 101 ways, but not the way it is defined in the book. (note, I know C++)
So far, we have only gone over the very basics of C++. So basically, we know variables, assignment, and basic casting.
In the book I am having trouble with this portion of the problem:
So I have the trivial code:
double n; cout<<"Number: "; cin >> n; cout <<endl<<static_cast<int>(n)<<endl;
But I realized this does not work for me. It will always truncate the decimal so that 1.9 -> 1 rather than the expected 1.9 -> 2
How do I fix this using only what I "know"? (as in, without round() or if statements and such)
Is this a standards compliance problem? At school I thought I had something similar working with Visual C++ 2005 on Windows XP 32 bit, but now I'm at my home trying to do the same thing and it's not working. My home compiler is gcc 3.3.5 on OpenBSD 64bit. Or could this be a typo in the book?
The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.
In C++, integers are not rounded. Instead, integer division truncates (read: always rounds towards zero) the remainder of the division.
ceil() ceil() function is rounding function that rounds the number to nearest integer values which is greater than the number. It always returns an integer value which is one more than the integer part of the float number.
round() in C++ round is used to round off the given digit which can be in float or double. It returns the nearest integral value to provided parameter in round function, with halfway cases rounded away from zero. Instead of round(), std::round() can also be used .
static_cast<int>(n+0.5)
Or static_cast<int>(n >= 0 ? n + 0.5 : n - 0.5)
for more proper behavior on negative n
.
Just so you know, this is not a problem with your compiler. In C++, when you convert a float to an integral type, the value is always truncated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With