简体   繁体   中英

Rounding with static_cast<int>?

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?

static_cast<int>(n+0.5)

或者static_cast<int>(n >= 0 ? n + 0.5 : n - 0.5)以获得更多关于负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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM