gpt4 book ai didi

正参数的 C 余数/模运算符定义

转载 作者:行者123 更新时间:2023-12-02 03:29:40 27 4
gpt4 key购买 nike

我在我应该修复的程序中发现了一个函数,该函数的 mod函数定义:

int mod(int a, int b)
{
int i = a%b;
if(i<0) i+=b;
return i;
}

有人告诉我ab顺便说一句,永远都是积极的......

嗯? if(i<0)

参数是 that

the result of the modulo operation is an equivalence class, and any member of the class may be chosen as representative

而且只是事后的想法

...; however, the usual representative is the least positive residue, the smallest nonnegative integer that belongs to that class, i.e. the remainder of the Euclidean division. However, other conventions are possible.

这意味着6 % 7可以返回 6 (到目前为止一切顺利),而且-1 。嗯……真的吗? (让我们忽略这个事实,所提出的实现并不能处理所有情况。)

我知道模运算在数学上是这样的。但后来有人告诉我 C %事实上“不实现模运算符,而是实现余数”。

那么,C 是如何定义 % 的?运算符(operator)?

在初稿中我只找到

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

这是否意味着 6 % 7总是6 ?或者可以是 -1 ,也?

最佳答案

根据标准:

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a. [ISO/IEC 9899:2011: 6.5.5]

这意味着 a 的符号保留在模数中。

 17 %  3  ->  2
17 % -3 -> 2
-17 % 3 -> -2
-17 % -3 -> -2
<小时/>

所以不,6%7 不能是 -1,因为提醒必须具有相同的股息符号。

关于正参数的 C 余数/模运算符定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58768191/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com