开发者

Rounding with static_cast<int>?

开发者 https://www.devze.com 2022-12-19 11:38 出处:网络
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++)

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 wo开发者_开发问答rking 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)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号