我在您的代码中进行了一些更改,以演示您尝试执行的操作,
#include
int main(){
short int n1, n2, somme;
printf("Enter the first number: ");
scanf("%hi", &n1);
printf("Enter the second number : ");
scanf("%hi", &n2);
somme = n1 + n2;
if( (n1 + n2) > 32767)
printf("negative overflow\n");
else if ( (n1 + n2) < -32768)
printf("positive overflow\n");
printf("int addition result is %d\n", n1 + n2);
printf("short addition result is %hi\n", somme);
return 0;
}
这是输出,
Enter the first number: -20000
Enter the second number : -20000
positive overflow
int addition result is -40000
short addition result is 25536
-----------------------------
Enter the first number: 20000
Enter the second number : 20000
negative overflow
int addition result is 40000
short addition result is -25536
所以,你的代码出了什么问题,
您正在使用 do...while 来检查条件 . 使用if-else .
您将总和存储在 short 中,并将其与 -32768 和 32767 进行比较 . 您试图通过将其与超出其可容纳的值范围的值进行比较来检查您的总和是否溢出 . Jérôme Leducq在他的answer中也解释了这一点 .