java的short和c语言short_在C语言中溢出short int

我在您的代码中进行了一些更改,以演示您尝试执行的操作,

#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中也解释了这一点 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值