[英]modulus returning incorrect amount in c program when a negative number is entered
有人可以帮我找出为什么在此C程序中输入负数时,该程序为何对模运算给出错误的答案吗?
我很确定导致问题的原因是scanf
函数。 当使用正整数时,将给出正确的答案。
代码如下:
#include <stdio.h>
int main()
{
int num1 = 0;
int num2 = 0;
int answer = 0;
puts("enter two number to find the modulus of...");
if (scanf("%3d %3d",&num1,&num2) != 2)
puts("something went wrong");
else {
answer = (num1 % num2);
printf("the modulus of %d and %d is: %d\n", num1, num2, answer);
}
}
在ANSI C中,没有为负输入定义模运算符结果的符号。 您可以从数学库( ref )中尝试div()
)。 它返回具有商和余数的结构,并且对于负输入可靠地工作。
或者,正如Alexey Frunze所建议的那样,您可以启用C99模式。 我懒得查找标准,但是进行了一些测试( gcc -std=c99
)表明结果的符号与左侧操作数的符号匹配。 因此,如果您想要ANSI兼容性, div()
仍然是最好的。
或者,您可以完全控制情况。 但是您必须选择正确的方法。 以下是Wikipedia的内容 。
int x, y, q, r; // all snippets: left-arg, right-arg, quotient, remainder
q = trunc( (double)x / y);
r = x - y * q;
q = floor( (double)x / y);
r = x - y * q;
q = y > 0 ? floor( (double)x / y) : ceiling( (double)x / y);
r = x - y * q;
接受答案后
在C中,自C99起,即使使用负操作数也可以很好地定义%
的结果。 见下文。
在C中, %
运算符在C中被称为“余数”,而不是“模数”。
要执行欧几里得除法和余数而不会导致截断,范围, double
转换问题**:
void Euclidean_divide_remainder(int a, int b, int *q, int *r) {
*q = a / b;
*r = a % b;
if (a < 0 && *r != 0) {
if (b < 0) { (*q)++; *r -= b; }
else { (*q)--; *r += b; }
}
}
void rtest(int a, int b) {
int eq, er;
Euclidean_divide_remainder(a, b, &eq, &er);
printf("f(%2d,%2d) / %2d %% %2d E/ %2d E%% %2d\n",
a, b, a / b, a % b, eq, er);
}
void rtest4(int a, int b) {
rtest(a, b);
rtest(a, -b);
rtest(-a, b);
rtest(-a, -b);
printf("\n");
}
int main(void) {
rtest4(7, 3);
return 0;
}
f( 7, 3) / 2 % 1 E/ 2 E% 1
f( 7,-3) / -2 % 1 E/ -2 E% 1
f(-7, 3) / -2 % -1 E/ -3 E% 2
f(-7,-3) / 2 % -1 E/ 3 E% 2
/运算符的结果是第一个操作数除以第二个的商。 %运算符的结果是余数 。 在这两个操作中,如果第二个操作数的值为零,则行为是不确定的。 C11dr§6.5.55
当整数相除时,/运算符的结果是代数商,其中舍弃了任何小数部分。 (这通常称为“向零截断”。)如果商
a/b
是可表示的,则表达式(a/b)*b + a%b
等于a
; 否则,a/b
和a%b
的行为均未定义。 C11dr§6.5.56
**例外:
a%0
的结果是不确定的。
对于2的补码, INT_MIN % -1
和INT_MIN E% -1
(在数学上应为0)是问题。 这是由于INT_MIN / -1
(数学上应为INT_MAX + 1
)引起的,因为答案不适合int
范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.