2016-07-01 32 views
1
#include <iostream> 
using namespace std; 


int arr[100] = {}; 
int terms; 
int maxterms; 
int sum = 0; 

int main() { 
    cout << "How many terms would you like to add?" << endl; 

    cin >> terms; 

    terms = maxterms; 

    for (int x = terms; x >= 0; x--) { 
     cout << "Number " << (((maxterms)-x) + 1) << ": "; 
     cin >> arr[(maxterms - x)]; 
     cout << endl; 
    } 

    for (int x = 0; x < maxterms; x++) { 
     sum += arr[x]; 
    } 

    cout << "Your sum is: " << sum; 

    return 0; 
} 

這個簡單的程序始終打印總和爲零,並且只提示用戶輸入一次。如何改進這段代碼,使其寫入數組的連續索引,然後返回它們的總和?寫入及閱讀從使用for循環數組和用戶輸入

+0

@SilentMonk我沒有看到這些是全局變量,所以這不是UB當然,你的答案是正確的。 – Holt

+0

@霍爾特,謝謝你的澄清。 – SilentMonk

回答

1

maxterms被初始化爲0,因爲它是一個全局變量。你是等式terms = maxterms你在哪裏覆蓋用戶的輸入爲0.

所以for (int x = 0; x < maxterms; x++)根本不運行。因此sum總是0。對於提示用戶輸入次數的循環也是如此。

此外,您提示用戶輸入的循環運行的時間爲terms+1次。

0

由於@SilentMonk指出,x = maxterms,所以循環退出。

您可以重新設計的循環,像這樣:

for (int x = maxterms; x >= 0; x--) 
{ 
    sum += arr[x]; 
} 

這裏x開始與它的價值等於maxterms,並下降,直到它的值是0,和arr[x]值加到sum每次迭代。

+0

我希望我能檢查兩個人作爲正確的答案,因爲你的延續也是非常有用的。 – jmantela

+0

謝謝您的確認。讓我們希望代碼編譯沒有錯誤。 –

-1

我只是檢查你的代碼,我看這行發現了這一點,

條款=最大項;

這將覆蓋用戶的輸入與一些隨機值,因爲你不是初始化maxterms。

我想你想複製用戶輸入最大項所以這樣做:

最大項=條款;

改變這一點,並嘗試。