对于c整数,1除以2是否可靠地等于0,而3/2 = 1,5/2 = 2等?

前端之家收集整理的这篇文章主要介绍了对于c整数,1除以2是否可靠地等于0,而3/2 = 1,5/2 = 2等?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有两个不同但相关大小的向量.较大的是(2 * RESOLUTION)INDEX_OFFSET(例如2050),较小的是简单的RESOLUTION(例如1024).我认为足够安全地假设uint16_t可用于包含向量索引.

通过将resultIndex递增2来执行通过较大向量的迭代.在每次迭代期间,对索引处的较小向量(resultIndex-INDEX_OFFSET)/ 2进行赋值.

本质上,代码依赖于以下假设:无论INDEX_OFFSET是奇数还是偶数,上述除以2将始终向下舍入,无论体系结构如何.例如,如果resultIndex为0或1,则预期为0,如果是2或3,则预期为1,依此类推.在上述参数范围内,这是一个安全的假设吗?

注:我承认‘Dividing integer types – Are results predictable?’的存在,但它似乎并不完全匹配.

解决方法

是;这是由语言保证:

[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 quotient a/b is representable in the type of the result,(a/b)*b + a%b is equal to a.

在3/2中,3和2都是整数操作数;这个操作的代数商是1.5,当你丢弃小数部分.5时,你得到1.这适用于你的其他例子,以及所有其他例子.

原文链接:https://www.f2er.com/c/117204.html

猜你在找的C&C++相关文章