C++ 用 static_cast<int> 舍入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2205211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rounding with static_cast<int>?
提问by Earlz
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++)
我觉得问这个问题真的很傻,因为我知道如何做 101 种方法,但不知道书中定义的方法。(注意,我知道 C++)
So far, we have only gone over the very basics of C++. So basically, we know variables, assignment, and basic casting.
到目前为止,我们只讨论了 C++ 的基础知识。所以基本上,我们知道变量、赋值和基本的转换。
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 nearestinteger 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
但我意识到这对我不起作用。它总是会截断小数,以便 1.9 -> 1 而不是预期的 1.9 -> 2
How do I fix this using only what I "know"? (as in, without round() or if statements and such)
如何仅使用我“知道”的内容来解决此问题?(例如,没有 round() 或 if 语句等)
Is this a standards compliance problem? At school I thoughtI 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?
这是标准合规性问题吗?在学校,我以为我在 Windows XP 32 位上使用 Visual C++ 2005 进行了类似的工作,但现在我在家里尝试做同样的事情,但它不起作用。我的家庭编译器是 OpenBSD 64 位上的 gcc 3.3.5。或者这可能是书中的错字?
回答by ephemient
static_cast<int>(n+0.5)
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
.
或者static_cast<int>(n >= 0 ? n + 0.5 : n - 0.5)
为了更正确的行为在negative 上n
。
回答by John Dibling
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.
请注意,这不是您的编译器的问题。在 C++ 中,当您将浮点数转换为整数类型时,该值始终会被截断。