C ++嵌套循环没有给我任何值

时间:2015-10-25 23:25:15

标签: c++ loops generator nested-loops

因此,这个嵌套循环应该为每个循环生成10个练习的随机分数 用户输入的学生。生成分数后,必须将它们全部添加并找到平均分数。但是,当我运行该程序时,它并没有给我任何值。这是代码:

int progExAvg, progExScore, studentAmt;
int counter = 0;
int progExTotal = 0;

srand(time(0));

cout << "Please enter how many students do you have in your class: ";
cin >> studentAmt;
cin.sync();

while (counter < studentAmt)
{
    for(int i = 0; i < 10; i++)
    {
        progExScore = rand() % 100 + 1;
        progExTotal = progExTotal + progExScore;
    }

    progExAvg = progExTotal / 10;



}
cout << progExAvg << endl;
return 0;

2 个答案:

答案 0 :(得分:1)

您永远不会增加counter,因此它始终小于studentAmt

while (counter < studentAmt)
{
    for(int i = 0; i < 10; i++)
    {
        progExScore = rand() % 100 + 1;
        progExTotal = progExTotal + progExScore;
    }

    progExAvg = progExTotal / 10;

    counter++;

}

答案 1 :(得分:1)

移动这些声明

int progExTotal = 0;
int progExTotal = 0;

和本声明

cout << progExAvg << endl;

在while循环中

这个宣言

int progExScore;
在for循环中

考虑到使用像10这样的幻数是个坏主意。最好使用含义名称。

此外,您还必须增加变量计数器。例如

const int TOTAL_EXERCISES =  10;

while (counter++ < studentAmt)
{
    int progExTotal = 0;
    int progExTotal = 0;

    for(int i = 0; i < TOTAL_EXERCISES; i++)
    {
        int progExScore = rand() % 100 + 1;
        progExTotal = progExTotal + progExScore;
    }

    progExAvg = progExTotal / TOTAL_EXERCISES;

    cout << progExAvg << endl;
}