微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对于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.jb51.cc/c/117204.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐