C ++中的整数舍入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21271815/
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
Integer rounding in C++
提问by user3064203
I was trying to use the formula below in c++. I have both variables declared as integers and I'm expecting them to round up but they seem to be rounding down. I have looked over this but cannot seem to find what is wrong. Any help would be greatly appreciated.
我试图在 C++ 中使用下面的公式。我将两个变量都声明为整数,我希望它们四舍五入,但它们似乎四舍五入。我已经查看了这个,但似乎无法找到问题所在。任何帮助将不胜感激。
int user_degrees_latitude, user_degrees_longitude;
const int lat_const=(-90)
const int long_const=(-180)
sector_latitude = (user_degrees_latitude - lat_const) / (10);
sector_longitude = (user_degrees_longitude - long_const) / (10);
The answer should be 13 for sector_latitude and 11 for sector_longitude but the computer rounds each down to 12 and 10 respectively.
答案应该是sector_latitude 的13 和sector_longitude 的11,但计算机分别四舍五入到12 和10。
回答by Glenn
In C++, integers are not rounded. Instead, integer division truncates (read: always rounds towards zero) the remainder of the division.
在 C++ 中,整数不四舍五入。相反,整数除法会截断(阅读:总是向零舍入)除法的余数。
If you want to get a rounding effect for positiveintegers, you could write:
如果你想得到正整数的舍入效果,你可以写:
sector_latitude = static_cast<int>(((user_degrees_latitude - lat_const) / (10.0)) + 0.5);
The addition of 0.5 causes the truncation to produce a rounding effect. Note the addition of the .0
on 10.0
to force a floating point divide before the addition.
添加 0.5 会导致截断产生舍入效果。请注意在加法之前添加.0
on10.0
以强制进行浮点除法。
I also assumed that sector_latitude
was an int with the casting.
我还假设这sector_latitude
是一个带有铸造的 int 。
回答by Baum mit Augen
Integer division in C++ always rounds towards zero. Use floating-point division to get "exact" results and use std::round
to round according to the normal rules:
C++ 中的整数除法总是向零舍入。使用浮点除法得到“精确”的结果并std::round
按照正常规则使用四舍五入:
sector_latitude = static_cast</*type of sector_latitude*/>( std::round( (user_degrees_latitude - lat_const) / 10.0 ));
The "10.0" (a double
) instead of "10" (an int
) tells the compiler to use floating-point arithmetic. It always chooses floating-point over integer calculation if a floating-point value like a double
is involved.
“10.0”(a double
)而不是“10”(an int
)告诉编译器使用浮点运算。如果double
涉及像 a 这样的浮点值,它总是选择浮点数而不是整数计算。