正参数的C余数/模运算符定义 [英] C remainder/modulo operator definition for positive arguments

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

问题描述

我在应该修复的程序中找到了一个定义了 mod 函数的函数:

I found a function in a program I am supposed to fix that has a mod function defined:

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

有人告诉我 a b 永远都是积极的...

I was told that a and b will always be positive by the way...

嗯? if(i< 0)?

参数是

取模运算的结果是一个等价类,并且可以选择该类的任何成员作为代表

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 .嗯...真的吗?(让我们忽略这样一个事实,即所提供的实现不能处理所有情况.)

That means that 6 % 7 could return 6 (so far so good), but also -1. Hrm... really? (Lets ignore the fact that the presented implementation does not handle all cases.)

我知道在数学上模运算是这样的.但是后来有人告诉我,C 实际上确实不是实现模运算符,而是实现余数".

I know that it is mathematically true that the modulo operation is like this. But then someone else told me that the C % does in fact "not implement the modulo operator but the remainder".

那么,C如何定义运算符?

So, how does C define the % operator?

在C-Draft中我只能找到

In the C-Draft I only find

/运算符的结果是第一个操作数除以第二;%运算符的结果是余数.在这两个操作中,如果第二个操作数为零,其行为是不确定的.

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 ?

Does this mean, that 6 % 7 is always 6? Or can it be -1, too?

推荐答案

永远:

  • a ==(a/b)* b + a%b
  • abs(a%b)<abs(b)
  • 如果 a b 为正,则 a%b 为正.
  • a == (a/b)*b + a%b
  • abs(a%b) < abs(b)
  • if a and b are positive, a % b is positive.

从C99开始,

  • a/b == trunc(a/b)
  • a%b 0 或带有 a 的符号.
  • a/b == trunc(a/b)
  • a%b is either 0 or has the sign of a.

认为 6%7 可能是 -1 的原因可能是因为缺少了 a b的结果肯定会得到肯定,并且缺少C99中的更改.

Thinking that 6 % 7 could be -1 is probably due to missing the fact that the result for a and b positive has always been guaranteed and missing the change in C99.

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

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