【问题标题】:average is outputting as inf平均输出为 inf
【发布时间】:2019-04-14 05:44:10
【问题描述】:

我正在尝试根据使用给出的数据文件给出的分数来计算班级的平均值。

我使用的公式是grade_Average = sum / i;

给出的数据文件是:

Joe Johnson 89
Susie Caldwell 67
Matt Baker 100
Alex Anderson 87
Perry Dixon 55

我得到的输出是

Johnson,Joe                    B
Caldwell,Susie                    D
Baker,Matt                    A
Anderson,Alex                    B
Dixon,Perry                    F

班级平均成绩

我不确定我的公式是否错误,或者公式是否放错地方。

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
    // Variable declarations: 
    string fName[10];
    string lName[10];
    float grade_Average;
    string file;
    string name;
    int scores[10];
    float sum = 0;
    char grade;
    int i = 0;

    ifstream din;

    // Function body: 

    cout << "Enter the name of the file. " << endl;
    cin >> file;

    din.open(file.c_str());

    if (!din)
    {
        cout << " Cannot open the input file. Please try again." << endl;
        return 0;
    }

    cout << setw(10) << setfill(' ')  << "Name" <<setw(20)<<setfill(' ')<< "Grade" << endl;

    while (!din.eof())
    {

        din >> fName[i];
        din >> lName[i];
        din >> scores[i];

        sum = sum + scores[i];

        switch (static_cast<int> (scores[i]/10))
        {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            grade = 'F';
            break;
        case 6:
            grade = 'D';
            break;
        case 7:
            grade = 'C';
            break;
        case 8:
            grade = 'B';
            break;
        case 9:
            grade = 'A';
            break;
        case 10:
            grade = 'A';
            break;
        default:
            cout << "Invalid score." << endl;

            i++;
        }

        name = lName[i] + ',' + fName[i];
        cout << setw(10) << setfill(' ') << name  << setw(20) << setfill(' ')<<(" ") << grade << endl;


    } 
    grade_Average = sum / i;
    cout << "Class average " << grade_Average << endl;

    din.close();

    return 0;
}

【问题讨论】:

  • stackoverflow.com/questions/5605125/…,并使用调试器。
  • 如果你使用 c++,一定要使用调试器 :)
  • i 仅在输入无效分数时才会增加。这意味着如果所有分数都有效,它将具有零值。然后在语句grade_average = sum/i 中使用它,其中sumgrade_average 的类型为float。使用 IEEE 浮点格式(不保证,但可能是您所拥有的)除以零会导致无穷大。

标签: c++ arrays while-loop


【解决方案1】:

您的 i++ 在默认块内。 i 变量很可能是 0。要么将 i++ 放在 switch 块之外,要么将它放在每个 break 语句之前。

【讨论】:

    【解决方案2】:

    i++ 位于 switch 块内和 default 案例中。它永远不会为给定的输入执行。因此在整个运行过程中i 将只是0。除以0 得到inf

    如果给出的条目超过10,您的程序也会失败(并且第一个问题已得到纠正)。如果需要这些数组,您应该使用std::vector&lt;std::string&gt;std::vector&lt;int&gt;push_back 而不是std::stringint 的原始数组。 (仅计算平均值,并不需要保存各个条目。)

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多