#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