简体   繁体   English

使用For循环和用户输入写入和读取数组

[英]Writing To & Reading From an Array using For Loops and User Input

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

This simple program always prints sum as zero, and only prompts for user input once. 这个简单的程序总是将sum打印为零,并且只提示用户输入一次。 How can this code be improved so that it writes to consecutive indexes of the array, then returns the sum of them? 如何改进此代码以便它写入数组的连续索引,然后返回它们的总和?

maxterms is initialised to 0 since it is a global variable. maxterms初始化为0,因为它是一个全局变量。 You are equation terms = maxterms where in you are overwriting user's input to 0. 您是等式terms = maxterms ,其中您将用户的输入覆盖为0。

So for (int x = 0; x < maxterms; x++) doesn't run at all. 所以for (int x = 0; x < maxterms; x++)根本不运行。 Hence the sum is 0 all the time. 因此, sum为0。 The same holds for the the loop where number of times user input is prompted. 对于提示用户输入次数的循环也是如此。

Also, the loop where you are prompting the user for input is running for terms+1 times. 此外,提示用户输入的循环正在运行terms+1次。

As @SilentMonk noted, x = maxterms, and so the loop exits. 正如@SilentMonk所指出的那样,x = maxterms,因此循环退出。

You can redesign the loop like so: 您可以像这样重新设计循环:

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

Here x starts with its value equal to maxterms , and decreases until its value is 0, and the value of arr[x] is added to sum every iteration. 这里x以其值等于maxterms ,并且减小直到其值为0,并且arr[x]的值被加到每次迭代sum

I just checked your code and i found this point by looking at this line, 我刚检查了你的代码,我通过查看这一行找到了这一点,

terms = maxterms; terms = maxterms;

this will overwrite the input of user with some random value as you are not initialising maxterms. 这将用一些随机值覆盖用户的输入,因为你没有初始化maxterms。

i think you wanted to copy user input to maxterms so do like this: 我想你想将用户输入复制到maxterms所以这样做:

maxterms = terms; maxterms = terms;

change this and try. 改变这一点并尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM