模数运算符更改 [英] Modulus operator changes

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

问题描述


$ 5.6 / 4在C ++ 03状态 - 如果两个
操作数都是非负数,那么
余数是非负数;如果不是,

$5.6/4 in C++03 states- "If both operands are nonnegative then the remainder is nonnegative;if not, the sign of the remainder is implementation-defined74).

其中注释74是


根据对ISO C的
修订版的工作进展,整数除法
的首选
算法遵循在ISO
Fortran标准中定义的规则,ISO / IEC 1539:1991,
其中商总是
向零舍入。

According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined inthe ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.

C ++ 0x状态 -

C++0x states -


$ 5.6 / 4-对于整数操作数,抛弃任何小数部分的代数商; 79 如果商a / b在结果类型中是可表示的,则(a / b)* b + a%b 等于a。

$5.6/4- "For integral operands the / operator yields the algebraic quotient with any fractional part discarded;79 if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

注意79说

这通常称为截断到零。

所以我有两个问题:


  • 有人可以解释这种向零截断的概念吗?

  • Can someone explain this concept of 'truncation towards zero'?

是否具有负操作数的模数是C ++ 0x中定义的行为?

Is modulus with negative operands a defined behavior in C++0x?

推荐答案

向零截断意味着通过选择下一个最接近零的整数将实数转换为整数。同样,你写下数字,忽略小数点后的所有数字,无论数字是正数还是负数。

Truncation towards zero means converting a real number to an integer by selecting the next integer nearest zero. Equivalently, you write the number down, and ignore everything after the decimal point, whether the number is positive or negative.

考虑11/4 = 2.75 - 如果截断

Consider 11/4 = 2.75 -- if you truncate this towards zero, you get 2.

考虑-11/4或11 / -4 = -2.75 - 如果你把它截断为零,你得到-2。

consider -11/4 or 11/-4 = -2.75 -- if you truncate this towards zero, you get -2.

对于一些数学运算,(a / b)* b + a%b == a很重要。如果我们必须使这个方程成立,并且我们也接受整数除法向零舍去,那么我们可以推导出运算符的操作如下:

It's important for some maths operations that (a/b)*b + a%b == a. If we must make this equation hold, and we also accept that integer division truncates towards zero, then we can deduce the operation of the % operator as follows:

a == 11, b == 4:
a/b == 2, 2*4 + a%b == 11, therefore a%b == 3.

a == -11, b == 4:
a/b == -2, -2 * 4 + a%b == -11, therefore a%b == -3.

a == 11, b == -4:
a/b == -2, -2 * -4 + a%b == 11, therefore a%b == 3.

a == -11, b == -4:
a/b == 2, 2 * -4 + a%b == -11, therefore a%b == -3.

这可能很混乱,但C ++ 0x是定义 a(a / b)* b + a%b == a 运算符$ c> $ c> a%b 此方程甚至对于负数也成立,因此对于负数定义 a%b

It might be confusing at first, but C++0x is defining the behaviour of the a%b operator using the equation (a/b)*b + a%b == a. This equation holds even for negative numbers, so a%b is defined for negative numbers.

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

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