#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循環數組和用戶輸入
@SilentMonk我沒有看到這些是全局變量,所以這不是UB當然,你的答案是正確的。 – Holt
@霍爾特,謝謝你的澄清。 – SilentMonk