C ++ for循环变量由另一个变量递增

时间:2017-02-11 23:47:36

标签: c++ for-loop

我一直在研究一个简单的成绩计算器,我在"实验室"选项吐出一个糟糕的结果,我正在寻找一个小数百分比,但我一直得到一个非常大的指数数字。

我遇到问题的具体部分是calclabavg()函数 - 准确的for循环。

我不是要求一个确切的解决方案,我只是想指出正确的方向,以便我可以自己解决问题。

事先非常感谢:)

float calclabavg(){//funciton that calculates user lab averages

    float x, vary, pointspos, sumpointspos, sumearned;

    cout << "How many labs in labs?" << endl;
    cin >> x;

    float totalpoints = 0;

    cout << "Do the points vary per lab? (Press 1 for yes, 0 for no)" << endl;
    cin >> vary;

    if (vary == 0){
        cout << "How many points were possible on each lab?" << endl;
        cin >> pointspos;
        sumpointspos = x * pointspos;
    }

    for (int i = 0; i < x; i++){
        float temp;
        cout << "What was your score on lab " << i + 1 << endl;
        cin >> temp;
        sumearned += temp;
        if (vary == 1){
            cout << "How mant points possible on lab " << i + 1 << endl;
            float pointsposvary;
            cin >> pointsposvary;
            sumpointspos += pointsposvary;
        }
        //pointspos = pointspos + temp;
    }

    return sumearned / sumpointspos;
}

1 个答案:

答案 0 :(得分:1)

好像你没有初始化sumearnedsumearned = 0.0;开头的语句calclabavg应该至少为您带来一步。顺便说一下:初始化其他变量也是很好的做法,使代码更稳定。