【发布时间】:2019-01-23 01:30:41
【问题描述】:
我最近一直在搞乱 C 语言,并开始接触整数重载的概念。我正在尝试创建一个程序来检测两个 32 位整数相乘是否能够适合另一个 32 位整数。
我了解整数溢出的概念以及整数如何最终溢出,但我一直在弄清楚这个程序的逻辑。到目前为止,这是我所拥有的:
int main() {
int min = INT_MIN;
int max = INT_MAX;
int num1, num2;
int x = num1 * num2;
printf("Please enter a number you would like to multiply: ");
scanf("%d", &num1);
printf("\nPlease enter a second number you would like to multiply: ");
scanf("%d", &num2);
if (num1 > max / num2){
printf("\nOverflow! - first case\n");
}
else if (num2 > max / num1){
printf("\nOverflow! - second case\n");
}
else if ((num1 > max - num2 && num2 > 0 ) ||
(num1 < max - num2 && num2 < 0)){
printf("\nOverflow! - third case\n");
}
else
printf("\nNot Overflow!\n");
return 0;
}
如您所见,我的程序可以检测到某些溢出情况,但其他几种情况(例如 -2 * 3 和 -2 * -3)会被我的条件捕获。
所以我所拥有的绝对行不通。有什么好的方法可以解决这个问题?
【问题讨论】:
标签: c integer overflow multiplication