下面的C程序的输出是什么?
null
C
#include <stdio.h> int main() { int a = 3, b = -8, c = 2; printf ( "%d" , a % b / c); return 0; } |
C++
#include <iostream> using namespace std; int main() { int a = 3, b = -8, c = 2; cout << a % b / c; return 0; } |
输出
1
%和/具有相同的优先级和从左到右的关联性。因此,首先执行%,结果是3,然后执行,结果是1。重点是, 在C中使用模运算符的情况下,左操作数的符号会附加到结果中 .
C
#include <stdio.h> int main() { // a positive and b negative. int a = 3, b = -8; printf ( "%d" , a % b); return 0; } |
C++
#include <iostream> using namespace std; int main() { int a = 3, b = -8; cout << a % b; return 0; } |
输出
3
C
#include <stdio.h> int main() { // a negative and b positive int a = -3, b = 8; printf ( "%d" , a % b); return 0; } |
C++
#include <iostream> using namespace std; int main() { // a negative and b positive int a = -3, b = 8; cout << a%b; return 0; } |
输出
-3
但是从余数的定义(如本文所述 https://en.wikipedia.org/wiki/Remainder )它应该永远是一个 最小正整数 这应该从a中减去,使其可被b整除(数学上,如果a=qb+r,则为0)≤ r
所以,在上面的例子中-3不是我们真正的余数,因为它是负数。
因此,在C/C++语言中,为了避免负余数,我们总是将余数作为(a%b+b)%b(将商添加到余数,然后再次获取余数)。
C
#include <stdio.h> int main() { // a and b both negative int a = -3, b = -8; printf ( "%d" , a % b); return 0; } |
C++
#include <iostream> using namespace std; int main() { // a and b both negative int a = -3, b = -8; cout << a % b; return 0; } |
输出
-3
当两个操作数都为正时,任何人都可以预测模运算符的输出。但对于负数,不同的语言给出不同的输出。
在C语言中,模数的计算公式为:,
a%n=a–(n*trunc(a/n))。
例如 8%-3=8-(-3*trunc(8/-3)) =8-(-3*trunc(-2.666..)) =8–(-3*-2){四舍五入到零} = 8 – 6 = 2
有关更多信息,请参阅 https://en.wikipedia.org/wiki/Modulo_operation
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END