0

私はstackoverflowコミュニティに不慣れで、コーディングも初めてなので、ここに投稿するコツとコーディングのルールを学ぶ間、事前にお詫び申し上げます。私は C++ を使用しており、CS161 の初級コンピューター サイエンス クラスに参加しています。

私は現在、コンピューターに保存されているデータ ファイルから読み取り、データを並べ替えて計算を行うように求める課題に取り組んでいます。この課題では、性別と学校の種類に基づいてテストの平均点を見つけます。すべてがコンパイルされ、プログラムが実行されますが、いくつかの問題があります。

最初の問題は私のエコーにあります。

    // echo the data file
    while (inData)
    {
    inData >> name >> sex >> school >> score;
    cout << name << sex << school << score << endl;

プログラムはデータをエコーし​​ますが、何らかの理由でリストの姓を 2 回エコーすることになります。また、(これが問題かどうかはわかりませんが)エコーするとき、名前、性別、学校、スコアの間のスペースをスキップしません。

2番目の問題は、計算が実行されていないことです。これは、何らかの「カウント」関連の命令が欠落しているためだと思いますが、できる限り困惑しています。

これが私のコードです。あなたの考えを教えてください:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
    //Declare variables to manipulate data
    char sex;
    string name;
    string school;
    string fileSource;
    string CC;
    string UN;
    int maleScore = 0;
    int femScore = 0;
    int unScore = 0;
    int ccScore = 0;
    double maleAvg;
    double femAvg;
    double unAvg;
    double ccAvg;
    double sumAvg = 0;
    int femCount = 0;
    int maleCount = 0;
    int ccCount = 0;
    int unCount = 0;
    int score;
    int sum;
    //Declare stream variables
    ifstream inData;
    ofstream outData;
    inData >> name >> sex >> school >> score;
    // Promt user for file location
    cout << "Please input file location: ";
    cin >> fileSource;

    // open output file and run program exit failsafe command
    inData.open(fileSource);
    if (!inData)
    {
        cout << "Cannot open input file. "
            << "Program will now terminate." << endl;
        return 1;
    }
    outData << fixed << showpoint << setprecision(2);

    // echo the data file
    while (inData)
    {
        inData >> name >> sex >> school >> score;
        cout << name << sex << school << score << endl;

        // while reading incoming data from file, execute the conditions

        // Male and female calculations
        if(sex=='M')
        {
            maleScore = maleScore +=score;
            ++maleCount;
        }
        else if(sex =='F')
        {
            femScore = femScore +=score;
            ++femCount;
        }

        // Community college and University calculations
        if(school == CC)
        {
            ccScore = ccScore +=score;
            ++ccCount;
        }
        else if(school == UN)
        {
            unScore = unScore +=score;
            ++unCount;
        }
        maleAvg = maleScore/maleCount;
    }

    // Male average output
    cout << maleAvg;

    femAvg = femScore/femCount;

    // Female average output
    cout << femAvg;

    ccAvg = ccScore/ccCount;

    // Community College average output
    cout << ccAvg;

    unAvg = unScore/unCount;

    // University average output
    cout << unAvg;
    sum = maleScore + femScore + ccScore + unScore;
    sumAvg = sum/12;
    cout << sumAvg;
    return 0;
}

また、私のコンパイラはプログラムを実行し続け、停止しません。コンパイラ ウィンドウの写真を撮りましたが、投稿する方法がわかりません。

4

1 に答える 1

1

コードにいくつか問題があります。一つずつ取っていきましょう。

ifstream inData;
ofstream outData;
inData >> name >> sex >> school >> score;

最後の行は何をしますか?inDataは開いていませんが、それから読み込もうとしています。

maleScore = maleScore +=score;

ここ(および他のいくつかの場所)では、+=演算子を誤って使用しています。+=次のように使用する必要があります。

maleScore += score;

または+次のように使用します:

maleScore = maleScore + score;

次に、これを行います。

if(school == CC)

さて、CCstd::stringあなたが初期化していないあなたのコードの中にあります(それはそれが空であることを意味します)。したがって、一致することはありません。したがって、if本体は実行されません。同じことが。でも起こりUNます。

さらに下に、ループ内に次の行があります。

maleAvg = maleScore/maleCount;

これは、ループを通過するたびに男性の平均を再計算します。これは必ずしも間違っているわけではありませんが(正しい結果が得られます)、ファイルの最初の人が女性の場合、maleCount0になるため、プログラムはゼロ除算でクラッシュします。女性がいない場合も同じことが起こります。入力ファイル、または大学または大学からのスコアがない場合。

最後にiostream::eof()、ループ内で使用することはお勧めできません。これについては、StackOverflowで詳しく読むことができます。ループ条件内のiostream :: eofが間違っていると見なされるのはなぜですか?

とはいえ、あなたの過ちはそれほど深刻ではなく、新しいプログラマーに典型的なものなので、落胆しないでください。これは、コードを調べてこの種のバグを見つける方法を学び、理解する機会と考えてください。ですから、これ以上面倒なことはせずに、このプログラムの改良版を見てみましょう。

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

using namespace std; // it's considered bad to do this - but since
                     // this is homework, we'll let it slide.

int main()
{
    //Declare variables to manipulate data    
    string name;
    string fileSource;

    int maleScore = 0;
    int femScore = 0;
    int unScore = 0;
    int ccScore = 0;
    int femCount = 0;
    int maleCount = 0;
    int ccCount = 0;
    int unCount = 0;

    //Declare stream variables
    ifstream inData;
    ofstream outData;

    // Promt user for file location
    cout << "Please input file location: ";
    cin >> fileSource;

    // open output file and run program exit failsafe command
    inData.open(fileSource);

    if(!inData)
    {
        cout << "Cannot open input file. "
             << "Program will now terminate." << endl;
        return 1;
    }    

    cout << "Reading data from '" << fileSource << "'" << endl;

    while(inData >> name)
    { // If we read a name, we can continue. Otherwise, we're done.     
        char sex;       
        int score;
        string school;

        inData >> sex >> school >> score;

        // Write the data out
        cout << "Processing " << name << " (" << sex << ") attending ";

        if(school == "UN")
            cout << "University";
        else if(school == "CC")
            cout << "Community College";

        cout << ". Score = " << score << endl;

        // Male and female calculations
        if(sex=='M')
        {
            maleScore +=score;
            maleCount++;
        }
        else if(sex =='F')
        {
            femScore +=score;
            femCount++;
        }

        // Community college and University calculations
        if(school == "CC")
        {
            ccScore +=score;
            ccCount++;
        }
        else if(school == "UN")
        {
            unScore +=score;
            unCount++;
        }       
    }

    // We do static_cast<double>(maleScore) / maleCount; to ensure that
    // the division is done using floating point and not integer 
    // arithmetic. We could have multiplied the numerator by 1.0 instead.

    if(maleCount != 0)
    {
        cout << "The average scores for males is: " << setprecision(2)
             << static_cast<double>(maleScore) / maleCount << endl;
    }

    if(femCount != 0)
    {
        cout << "The average score for females is: " << setprecision(2)
             << static_cast<double>(femScore) / femCount << endl;
    }

    if(ccCount != 0)
    {
        cout << "The average score for Community Colleges is: " << setprecision(2)
             << static_cast<double>(ccScore) / ccCount << endl;
    }

    if(unCount != 0)
    {
        cout << unScore << "/" << unCount << endl;

        cout << "The average score for Universities is: "  << setprecision(2)
             << static_cast<double>(unScore) / unCount << endl;
    }

    // In this case we will use the multiplication technique instead:   
    cout << "The 'sum' average is: " << setprecision(2)
         << (1.0 * (maleScore + femScore + ccScore + unScore)) / 12 << endl;

    return 0;
}
于 2013-02-13T22:21:11.073 に答える