关于取模运算

zeng028888 2012-03-26 08:25:57
c++primer 里面说, 如果只有一个操作数为 负数,除法和取模的值取决于机器

比如 21%(-5)// 结果为 1 or -4 比如 21 / 5 ; // 结果为 -4 or -5

但是,后面又说,求模操作结果值的符号可以依据分子(被除数)或者分母(除数)的符号而定。 如果求模的结果随分子的符号,则结果向零取整,如果求模的结果随分母的符号,则结果向负无穷取整。

那到底是取决于机器,还是依据分子或者分母的符号呢????
...全文
596 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
一根烂笔头 2012-03-26
  • 打赏
  • 举报
回复
下面是MSDN上的说明,看明白了就清楚了!

% The result of the remainder operator is the remainder when the first operand is divided by the second. When the division is inexact, the result is determined by the following rules:
If the right operand is zero, the result is undefined.

If both operands are positive or unsigned, the result is positive.

If either operand is negative and the result is inexact, the result is implementation defined. (See the Microsoft Specific section below.)

Microsoft Specific —>

In division where either operand is negative, the direction of truncation is toward 0.

If either operation is negative in division with the remainder operator, the result has the same sign as the dividend (the first operand in the expression).

pengzhixi 2012-03-26
  • 打赏
  • 举报
回复
反正c++标准是没有规定符号怎么决定。
/and %
If both operands are nonnegative then the remainder is nonnegative;
if not, the sign of the remainder is implementation-defined74).

我记得深入理解计算机系统上是有说明的。
muyi66 2012-03-26
  • 打赏
  • 举报
回复
既取决于机器,又依据分子分母符号。两者并不矛盾。

取决于机器是指得到余数的符号正负。取决于分子分母指的则是在机器已经确定符号的情况下绝对值如何取整。
nice_cxf 2012-03-26
  • 打赏
  • 举报
回复
取决于编译器的实现,如果分子分母符号不同,假定分子为正,如果编译器按照分子的符号来处理,那么结果为正
,如果编译器按照分母的符号来处理,那么结果为负

64,344

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧