对于 C++ 整数,1 除以 2 是否可靠地等于 0,3/2 = 1、5/2 = 2 等等?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14282989/
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
With c++ integers, does 1 divided by 2 reliably equal 0, and 3/2 = 1, 5/2 = 2 etc.?
提问by mosi
There are two vectors of differing, yet related sizes. The larger is (2 * RESOLUTION) + INDEX_OFFSET
(e.g. 2050) and the smaller is simply RESOLUTION
(e.g. 1024). I believe it safe enough to assume that uint16_t
can be used to contain the vector index.
有两个大小不同但相关的向量。较大的是(2 * RESOLUTION) + INDEX_OFFSET
(例如2050),较小的是RESOLUTION
(例如1024)。我相信它足够安全,uint16_t
可以用来包含向量索引。
Iteration through the larger vector is performed by incrementing resultIndex
by 2. During each iteration, an assignment is made to the smaller vector at the index (resultIndex - INDEX_OFFSET) / 2
.
对较大向量的迭代通过增加resultIndex
2来执行。在每次迭代期间,对索引处的较小向量进行分配(resultIndex - INDEX_OFFSET) / 2
。
Essentially, the code relies on the assumption that, whether INDEX_OFFSET
is odd or even, the above division by 2 will always round down, regardless of architecture. For example, if resultIndex
is 0 or 1, then 0 is expected, if is it 2 or 3 then 1 is expected, and so on. Is this a safe assumption, within the parameters above?
本质上,代码依赖于这样的假设:无论INDEX_OFFSET
是奇数还是偶数,上述除以 2 的结果总是向下取整,无论架构如何。例如,如果resultIndex
是 0 或 1,则预期为 0,如果是 2 或 3,则预期为 1,依此类推。在上述参数范围内,这是一个安全的假设吗?
N.B. I acknowledge the existence of 'Dividing integer types - Are results predictable?'but it does not seem to be an exact match.
注意,我承认存在“划分整数类型 - 结果是否可预测?” 但它似乎并不完全匹配。
回答by Lightness Races in Orbit
Yes; this is guaranteed by the language:
是的; 这是由语言保证的:
[C++11: 5.6/4]:
The binary/
operator yields the quotient, and the binary%
operator yields the remainder from the division of the first expression by the second. If the second operand of/
or%
is zero the behavior is undefined. For integral operands the/
operator yields the algebraic quotient with any fractional part discarded;if the quotienta/b
is representable in the type of the result,(a/b)*b + a%b
is equal toa
.
[C++11: 5.6/4]:
二元/
运算符产生商,二元%
运算符产生第一个表达式除以第二个表达式的余数。如果/
or的第二个操作数%
为零,则行为未定义。对于整数操作数,/
运算符产生代数商,其中任何小数部分都被丢弃;如果商a/b
可在结果的类型中表示,(a/b)*b + a%b
则等于a
。
In 3/2
, both 3
and 2
are integral operands; the algebraic quotient of this operation is 1.5
, and when you discard the fractional part .5
, you get 1
. This holds for your other examples and, well, all other examples.
在 中3/2
,3
和2
都是整数操作数;此运算的代数商为1.5
,当您丢弃小数部分时.5
,您会得到1
。这适用于您的其他示例以及所有其他示例。