2017-05-26 32 views
2

我是新手!C編程兩個整數之間的所有整數的總和

我應該從用戶得到2個整數,並打印結果(這兩個整數之間的所有數字的總和)。

我還需要確保用戶鍵入正確的數字。 第二個數字應該比第一個數字更大。

如果條件不滿足,我必須打印「第二個數字應該大於第一個數字」。並再次獲取用戶的號碼,直到用戶輸入符合條件的正確號碼。

所以如果我編程它的權利,程序的一個例子會是這樣的。

類型第一數目(整數):10

類型第二數目(整數):1

第二數目應比第一個更大。

類型第一數目(整數):1種

類型第二數目(整數):10

結果:55

結束

我認爲,我必須做兩個循環,但我似乎無法弄清楚如何。 我的英語是有限的,爲了幫助你理解這個測驗,我將在下面添加我的流程圖。

Flowchart

我嘗試過許多不同的方法,我能想到的,但似乎沒有任何工作。 這是我現在結束的代碼。 但是這也行不通。

#include <stdio.h> 
void main(void) 
{ 
    int a = 0; 
    int b = 0; 
    int total_sum = 0; 
    printf("Type the first number : \n"); 
    scanf("%d", &a); 
    printf("Type the second number : \n"); 
    scanf("%d", &b); 
    while (a > b) { 
     printf("The second number should be bigger than the first one.\n"); 
     printf("Type the first number : \n"); 
     scanf("%d", &a); 
     printf("Type the second number : \n"); 
     scanf("%d", &b); 
    } 
    while (a <= b) { 
     total_sum += a; 
     a++; 
    } 
    printf("Result : \n", total_sum); 
} 
+1

歡迎StackOverflow的。 如果您正在尋找有關調試代碼的幫助,請參閱https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Yunnosch

+1

它以哪種方式無效?崩潰?掛?錯誤的輸出? – Yunnosch

+4

您在最後一次'printf'調用中忘記了格式說明符。 – George

回答

0

糾正後,您的代碼應該運行。社區已經指出你的代碼有很多錯誤。下面是一個融和的解決方案:

#include <stdio.h> 
int main(void) 
{ 
    int a = 0; 
    int b = 0; 
    int correctInput=0; 
    int total_sum = 0; 
    do 
    { 
     printf("Type the first number : \n"); 
     scanf("%d", &a); 
     printf("Type the second number : \n"); 
     scanf("%d", &b); 
     if(a<b) 
      correctInput=1; 
     else 
      printf("The second number should be bigger than the first one.\n"); 
    } 
    while (correctInput ==0) ; 

    while (a <= b) { 
     total_sum += a; 
     a++; 
    } 
    printf("Result : %d \n" , total_sum); 
    return 0; 
} 
+3

'如果(A> B)' - >'如果(A

+1

也,類型的東西而不是數字,看到有很大無端環;) –

+1

你應該檢查scanf()調用是否成功。作爲一個半正式的用戶界面,你應該限制嘗試的次數,儘管這個問題沒有說明。十是一個好數字;如果他們在十次嘗試中無法正確判斷,他們可能永遠不會。 –

1

使用循環來概括的數字相反的,我們可以用數學公式。

第一N個整數的總和= N *(N + 1)/ 2

#include <stdio.h> 
int main(void) 
{ 
    int a = 0; 
    int b = 0; 
    int sum; 

    //Run infinite loop untill a>b 
    while(1) 
    { 
     printf("Type the first number : "); 
     scanf("%d", &a); 
     printf("Type the second number : "); 
     scanf("%d", &b); 
     if(a>b) 
     { 
      printf("The second number should be bigger than the first one.\n"); 
     } 
     else 
     { 
      break; 
     } 
    } 

    //Reduce comlexity of looping 
    sum=((b*(b+1))-(a*(a-1)))/2; 

    printf("Result : %d " , sum); 
    return 0; 
} 
相關問題