简体   繁体   English

C语言中的short int溢出

[英]overflow short int in language C

I'm trying to make a program that show short int overflows in C. In my program you enter two short int and I add them. 我正在尝试制作一个在C中显示int短整数溢出的程序。在我的程序中,您输入两个short int并添加它们。 If the addition is superior to 32767 we have a negative overflow and if the addition is inferior to -32678 we have a positive overflow. 如果加法大于32767,则我们有一个负溢出,如果加法小于-32678,我们有一个正溢出。

Now my problem is that my program refuses to respect any of the condition when using if . 现在我的问题是我的程序在使用if时拒绝遵守任何条件。 But when I use do while my program consider that I respect the two condition at the same time. 但是当我do while程序中使用do while我认为我同时尊重两个条件。

short int n1, n2, somme;
printf("Enter the first number: ");
scanf("%hi", &n1);
printf("enter the second number : ");

scanf("%hi", &n2);

somme= n1 + n2;
    do
    {
    printf("negative overflow\n");
    }while (somme>32767);
    do
    {
    printf("negative overflow\n");
    }while ( somme<-32768);

printf("the result is %hi", somme);

Sorry for my english. 对不起我的英语不好。 and thanks for reading, please help. 感谢您的阅读,请提供帮助。

I made a few changes in your code to demonstrate what you were trying to do, 我对您的代码进行了一些更改,以演示您要执行的操作,

#include<stdio.h>
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;
}

And here is the output, 这是输出,

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

So, what was wrong in your code is that, 所以,您代码中的错误是

  • You were using do...while to check for conditions. 您正在使用do...while检查条件。 Use if-else . 使用if-else
  • You were storing the sum in short and comparing that with -32768 and 32767 . short ,您存储的是总和并将其与-3276832767进行比较。 You are trying to check if your sum overflowed by comparing it with values which are outside the range of values it can hold. 您正在尝试通过将总和与可容纳的值范围之外的值进行比较来检查总和是否溢出。 This is also explained by Jérôme Leducq in his answer . JérômeLeducq回答中对此进行了解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM