运算符对C ++ 11进行模更改? [英] operator modulo change in c++ 11?

查看:89
本文介绍了运算符对C ++ 11进行模更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C ++运算符的百分比保证

Possible Duplicate:
C++ operator % guarantees

在c ++ 98/03中

In c++ 98/03

5.6-4

二进制/运算符产生商,二进制%运算符 产生第一个表达式除以的余数 第二.如果/或%的第二个操作数为零,则行为为 不明确的;否则(a/b)* b + a%b等于a. 如果两个操作数 为非负数,则其余为非负数;如果不是,则为 其余的是实现定义的.

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

二进制/运算符产生商,二进制%运算符 产生第一个表达式除以的余数 第二.如果/或%的第二个操作数为零,则行为为 不明确的.对于整数操作数,/运算符产生代数 丢弃任何小数部分的商; 81如果商a/b为 可表示为结果的类型,(a/b)* b + a%b等于a.

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.

您会看到缺少符号位的实现定义,这会发生什么?

As you can see the implementation-defined for the sign bit is missing, what happens to it ?

推荐答案

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

The behaviour of % was tightened in C++11, and is now fully specified (apart from division by 0).

截断取零和标识(a/b)*b + a%b == a的组合表示a%b对于正a始终为正,对于负a始终为负.

The combination of truncation towards zero and the identity (a/b)*b + a%b == a implies that a%b is always positive for positive a and negative for negative a.

其数学原因如下:

÷为数学除法,而/为C ++除法.

Let ÷ be mathematical division, and / be C++ division.

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

For any a and b, we have a÷b = a/b + f (where f is the fractional part), and from the standard, we also have (a/b)*b + a%b == a.

a/b会截断到0,因此我们知道,如果a÷b为正,而小数部分为a÷b为负,则小数部分将始终为正:

a/b is known to truncate towards 0, so we know that the fractional part will always be positive if a÷b is positive, and negative is a÷b is negative:

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

a÷b = a/b + f可以重新排列以给出a/b = a÷b - f. a可以扩展为(a÷b)*b:

a÷b = a/b + f can be rearranged to give a/b = a÷b - f. a can be expanded as (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),所以:

Recall from earlier that sign(f)==sign(a)*sign(b), so:

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

这篇关于运算符对C ++ 11进行模更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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