2015-11-03 78 views
0

我试图做一个程序,显示在C短短的int溢出。在我的程序中,输入两个短整型,然后我添加它们。如果加法优于32767,我们有负溢出,如果加法低于-32678,我们有一个正溢出。溢出语言C中的短整数

现在我的问题是,当使用if时,我的程序拒绝尊重任何条件。但是当我使用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); 

对不起,我的英语。并感谢阅读,请帮助。

+1

你是不是要用'if'而不是'do ... while'? –

+0

你知道'做什么'的作品吗?这不是“if”的替代。即使条件不满足,块中的代码也会执行一次。所以“但是当我使用程序时,我认为我同时尊重这两个条件”,这是错误的。你的程序在逻辑上不正确。 –

+0

我尝试过“如果”但它不起作用。 –

回答

1

我做你的代码的一些变化来证明你正在尝试做的,

#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; 
} 

这里是输出,

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中,并将其与-3276832767进行比较。您正试图通过将其与超出其可容纳的值范围的值进行比较来检查您的总和是否已经溢出。这也可以通过Jérôme Leducq在他的answer中解释。
+0

非常感谢你,我认为不同的是当你使用if((n1 + n2)<32 ...)而不是if(somme <32 .....) –

+0

@AmaraDiagana正确! '(n1 + n2)'评估为“int”而不是“short”。因此,比较按预期工作。 –

+1

不能保证'int'大于'short',也不能保证'short'是16位。一般来说,你不应该这样做怪异的假设,而是使用'stdint.h'类型。 – Lundin