2017-02-20 75 views
0

你好對不起這個可能是一個愚蠢的問題,但我只是提出我的第一個步驟,在C和我找不到任何明確的答案,所以:問題與總和在循環

比方說,我有總結一些整數,爲什麼表達式sum += sum,在這個代碼中只返回輸入時間2的最後一個數字(lastNumber * 2)?

unsigned int count = 0, sum = 0; 
printf("How many numbers do you want to sum: "); 
scanf("%u", &count); 

for (int i = 1; i <= count; ++i) { 
    printf("enter the integer: "); 
    scanf("%u", &sum); 
    sum += sum; 
} 

printf("the sum of all the %u numbers is: %u\n", count, sum); 

PS:如果我sum += x替換表達式此問題得到解決; 但我不明白爲什麼。

+0

'sum + = sum' =='sum = sum + sum' sure it'sum * 2' –

+2

如何使用一個多變量進行輸入? –

+0

請縮進您的代碼。 –

回答

1

隨着線

scanf ("%u", &sum); // Let's say the user enters "7" 

您覆蓋與用戶輸入一個新值,每次迭代和的值。然後你

sum = sum + sum; // equivalent to sum = 7 + 7; 

再次添加用戶變量可以避開,通過使用兩個變量:

int sum = 0; 
int userIn = 0; 
scanf ("%u", &userIn); // userIn has now the value of the user input 
sum += userin; // Add that value to the sum 
0

當你在做的scanf(...,&總和)你真正覆蓋它的值。 因此,每一個重複你什麼都不做。 通常,將變量分配給各個目的是一種很好的做法。這意味着變量包含總和,另一個獲取用戶輸入。

0

你可能想這樣的:

unsigned int count = 0, sum = 0; 
printf("How many numbers do you want to sum: "); 
scanf("%u", &count); 

for (int i = 1; i <= count; ++i) { 
    printf("enter the integer: "); 
    unsigned int value; 
    scanf("%u", &value); 
    sum += value; // or sum = sum + value; 
} 

printf("the sum of all the %u numbers is: %u\n", count, sum); 
0

因爲sum += sum;相當於sum = sum + sum;和相當於(2 *和)(總和+總和)。