不能调零? [英] Can't Mod Zero?

查看:132
本文介绍了不能调零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 X%0 无效的表达式?

我一直认为 X %0 应该等于X.由于你不能除以零,应该不是答案自然是余数,X(剩下的一切)?

I always thought X % 0 should equal X. Since you can't divide by zero, shouldn't the answer naturally be the remainder, X (everything left over)?

推荐答案

C ++标准(2003)在§5.6/ 4中说,

The C++ Standard(2003) says in §5.6/4,


...]如果/或%的第二个操作数为零,则行为为 undefined ; [...]

也就是说,以下表达式invoke undefined-behavior(UB):

That is, following expressions invoke undefined-behavior(UB):

X / 0; //UB
X % 0; //UB






注意 -5%2 不等于 - (5%2)(Petar似乎在他的回答评论中建议)。它是实现定义的。规范说(§5.6/ 4),


Note also that -5 % 2 is NOT equal to -(5 % 2) (as Petar seems to suggest in his comment to his answer). It's implementation-defined. The spec says (§5.6/4),


[...]如果两个操作数都是非负的,那么余数是非负的; 如果不是,余数的符号是​​实现定义的

这篇关于不能调零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆