簡體   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;
}

這個簡單的程序總是將sum打印為零,並且只提示用戶輸入一次。 如何改進此代碼以便它寫入數組的連續索引,然后返回它們的總和?

maxterms初始化為0,因為它是一個全局變量。 您是等式terms = maxterms ,其中您將用戶的輸入覆蓋為0。

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

此外,提示用戶輸入的循環正在運行terms+1次。

正如@SilentMonk所指出的那樣,x = maxterms,因此循環退出。

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

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

這里x以其值等於maxterms ,並且減小直到其值為0,並且arr[x]的值被加到每次迭代sum

我剛檢查了你的代碼,我通過查看這一行找到了這一點,

terms = maxterms;

這將用一些隨機值覆蓋用戶的輸入,因為你沒有初始化maxterms。

我想你想將用戶輸入復制到maxterms所以這樣做:

maxterms = terms;

改變這一點並嘗試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM