Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding with static_cast<int>?

Tags:

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:

  • prompt the user to input a decimal number
  • Convert that number to the nearest integer and print it to the screen

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?

like image 618
Earlz Avatar asked Feb 05 '10 05:02

Earlz


People also ask

What does static_cast int do?

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.

Does C++ int round up?

In C++, integers are not rounded. Instead, integer division truncates (read: always rounds towards zero) the remainder of the division.

How do you round a float to an int in C++?

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.

How do you round off in C++?

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 .


2 Answers

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.

like image 63
ephemient Avatar answered Oct 06 '22 23:10

ephemient


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.

like image 29
John Dibling Avatar answered Oct 06 '22 23:10

John Dibling