do while中的数组值没有传递给下一个

时间:2015-02-14 18:08:21

标签: c++ arrays

我对c ++相当新,并且在通过do while循环传递数组并计算平均值时遇到问题。以下是我的代码,有人会指出我正确的方向吗?

#include <iostream>

using namespace std;

int main() {
    int marks[5], sum = 0, g, avg=0;
    do {
        cout << "enter a mark: ";
        cin >> marks[g];
        if (marks[g] < 0 || marks[g] > 100)
            "Invalid Mark, start over";
        marks[g++];
    } while(g <= 5);
    do {
        sum += marks[g++];
        avg = sum/5;
    } while(g <= 5);
    cout << "The average of the marks is: " << avg << endl;
}

3 个答案:

答案 0 :(得分:3)

您从未初始化索引变量g,应将其初始化为

int g = 0;

另外我建议您的第一个循环类似

while (g < 5)
{
    int value;
    cout << "enter a mark: ";
    cin >> value;

    if (value < 0 || value > 100)
    {
        "Invalid Mark, enter again";
    }
    else
    {
        marks[g] = value;
        ++g;
    }
}

同样,最后一个循环是

for {int i = 0; i < 5; ++i)
{    
    sum += marks[i];
}
avg = sum/5;

答案 1 :(得分:0)

首先,使用

g初始化为0
int g = 0;

其次,改变

while(g <= 5);

while(g < 5);

因为marks[]的大小为5,所以可访问的索引是0到4。

更正后的代码:

#include <iostream>
using namespace std;
int main()
{
    int marks[5], sum = 0, g = 0, avg=0;
    do
    {
        cout << "enter a mark: ";
        cin >> marks[g];

        if (marks[g] < 0 || marks[g] > 100)
        {
            "Invalid Mark, start over";
        }
        else g++;
    }
    while(g < 5);
g = 0; //Set g to zero to restart counting.
do {

    sum += marks[g++];
    avg = sum/5;
}
while(g < 5);
cout << "The average of the marks is: " << avg << endl;
}

答案 2 :(得分:0)

变量g未正确初始化。也是数组访问超出范围。正确的代码应该是:

#include<iostream>

using namespace std;

int main()

{
    int marks[5], sum = 0, g = 0, avg=0;

    do
    {
        cout << "enter a mark: ";
        cin >> marks[g];

        if (marks[g] < 0 || marks[g] > 100)
        {
            "Invalid Mark, start over";
        }
        else
            marks[g++];

    }
    while(g < 5);
    g = 0;

    do {

        sum += marks[g++];
        avg = sum/5;
    }
    while(g < 5);

    cout << "The average of the marks is: " << avg << endl;

    system("pause");

}