2015-11-03 80 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