写作&使用For循环和用户输入从数组中读取

时间:2016-07-01 07:20:45

标签: c++ arrays c++11 for-loop

#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;
}

这个简单的程序总是将sum打印为零,并且只提示用户输入一次。如何改进此代码以便它写入数组的连续索引,然后返回它们的总和?

3 个答案:

答案 0 :(得分:1)

maxterms初始化为0,因为它是一个全局变量。你是等式terms = maxterms,你在其中将用户的输入覆盖为0。

所以for (int x = 0; x < maxterms; x++)根本没有运行。因此sum始终为0。对于提示用户输入次数的循环也是如此。

此外,提示用户输入的循环正在运行terms+1次。

答案 1 :(得分:0)

正如@SilentMonk所说,x = maxterms,因此循环退出。

您可以像这样重新设计循环:

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

此处x以等于maxterms的值开头,并在其值为0之前减小,并且arr[x]的值每次迭代都会添加到sum。< / p>

答案 2 :(得分:-1)

我刚检查了你的代码,我通过查看这一行找到了这一点,

terms = maxterms;

这会用一些随机值覆盖用户的输入,因为你没有初始化maxterms。

我认为你想将用户输入复制到maxterms,所以这样做:

maxterms = terms;

改变这一点并尝试。