使用C ++中的负整数除法舍入 [英] Integer division rounding with negatives in C++

查看:125
本文介绍了使用C ++中的负整数除法舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 a b 都是 int b 为非零。考虑在以下情况下执行 a / b 的结果:

Suppose a and b are both of type int, and b is nonzero. Consider the result of performing a/b in the following cases:


  1. a b 均为非负。

  2. / code>和 b 均为负。

  3. 其中一个为负。

  1. a and b are both nonnegative.
  2. a and b are both negative.
  3. Exactly one of them is negative.

在情况1中,结果向下取整为最接近的整数。但标准对案例2和3有什么看法?我发现在互联网上浮动的一个旧草案表明,它是实现相关的(是的,即使情况2),但委员会倾向于使它总是向零。有谁知道(最新)标准说什么?

In Case 1 the result is rounded down to the nearest integer. But what does the standard say about Cases 2 and 3? An old draft I found floating on the Internet indicates that it is implementation dependent (yes, even case 2) but the committee is leaning toward making it always 'round toward zero.' Does anyone know what the (latest) standard says? Please answer only based on the standard, not what makes sense, or what particular compilers do.

推荐答案

根据2008年5月修订版,

According to the May 2008 revision,

您是对的:


,二进制%运算符从第一个表达式除以秒得到余数。如果/或%的第二个操作数为零,则该行为未定义;否则(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-defined75).

注意75说:


根据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 in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.

C ++在这方面可能会滞后C。

Chances are that C++ will lag C in this respect. As it stands, it's undefined but they have an eye towards changing it.

我和Stroustrup和同一个委员会的成员在同一个部门工作,这是不确定的。事情需要AGES来完成,它的无休止的政治。如果它似乎愚蠢,它可能是。

I work in the same department as Stroustrup and with a member of the committee. Things take AGES to get accomplished, and its endlessly political. If it seems silly, it probably is.

这篇关于使用C ++中的负整数除法舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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