c++ - C++ 11中的运算符模数变化?

标签 c++ c++11 language-lawyer modulo c++03

<分区>

Possible Duplicate:
C++ operator % guarantees

在 C++ 98/03 中

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; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

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

如您所见,缺少为符号位定义的实现,它会发生什么情况?

最佳答案

% 的行为在 C++11 中得到加强,现在已完全指定(除以 0 除外)。

向零截断和恒等式 (a/b)*b + a%b == a 的组合意味着 a%b 对于正数总是正数a 和 negative 表示负 a


其数学原因如下:

÷为数学除法,/为C++除法。

对于任何 a 和 b,我们有 a÷b = a/b + f(其中 f 是小数部分),并且根据标准,我们还有 (a/b)*b + a%b == a.

a/b 已知会向 0 截断,因此我们知道如果 a÷b 为正,负是a÷b是负:

sign(f) == sign(a)*sign(b)

a÷b = a/b + f 可以重新排列为 a/b = a÷b - fa可以展开为(a÷b)*b:

(a/b)*b + a%b == a => (a÷b - f)*b+a%b == (a÷b)* b.

现在左侧也可以展开了:

(a÷b)*b - f*b + a%b == (a÷b)*b

a%b == f*b

回想一下之前的sign(f)==sign(a)*sign(b),所以:

sign(a%b) == sign(f*b) == sign(a)*sign(b)*sign(b) == sign(a)

关于c++ - C++ 11中的运算符模数变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100711/

相关文章:

c++ - qt + mysql 在另一台电脑上启动应用程序

c++ - 为什么 char* 中不包含行结束符?

C++11 树上的异步操作

c++ ->> 运算符的使用

c++ - C++ 11:将 vector 元素作为线程传递到线程函数中

c++ - 使用临时存储区 : is it allowed? 复制可简单复制的类型

c++ - 在具有自动存储期限的 const 变量上放置 new 是否合法?

c++ - 需要解决 Makefile 读取 Storm 数据程序的问题

c++ - 在非事件联盟成员上使用 `std::addressof` 是否明确

c++ - boost::signals2 插槽作为非静态函数成员?