本文介绍了正参数的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)?

参数是

这只是事后的想法

这意味着 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

这是否意味着 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余数/模运算符定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:41