0

私の前スレを見てくださった方、前回はごめんなさい。うっかりミスやタイプミスだらけでした。これは私の課題です:

「ユーザーが入力ステートメントを介して一連の負でない数を入力できるようにするプログラムを作成します。入力プロセスの最後に、プログラムは次のように表示します: 奇数の数とその平均; 偶数の数およびその平均; 入力された数値の総数。負の値を入力して入力プロセスを停止できるようにします。この終了条件がユーザーに通知されていることを確認してください。

そして、ここに私のコードがあります:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int number, total1=0, total2=0, count1=0, count2=0;
    do
    {
        cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
        cin >> number;

        if(number % 2 == 0)
        {
            count1++;
            total1+=number;
        }
        else if (number >= 0)
        {
            count2++;
            total2+=number;
        }
    }
    while (number>=0);
        int avg1 = total1/count1;
        int avg2 = total2/count2;
        cout << "The average of your odd numbers are: " << avg1 << endl;
        cout << "The average of your even numbers are " << avg2 << endl;
}

正常に動作しているように見えますが、プログラムを終了するために負の数を入力すると、残りの平均化された数に含まれます。これを回避するためのアドバイスはありますか?私はそれが可能であることを知っていますが、その考えは私を逃れます.

4

3 に答える 3

2

メインループは次のようになります。

#include <iostream>

for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
    // process n
}

または、診断を発行する場合は、次のようにします。

for (int n; ; )
{
    std::cout << "Enter a number: ";

    if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }

    if (n < 0) { std::cout << "Non-positve number!\n"; break; }

    // process n
}
于 2012-10-29T00:38:51.690 に答える
1

ここの後:

cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;

数値が負かどうかをすぐに確認する

if(number < 0) break;

これで、数値が負かどうかを確認する際に do-while ループを使用する必要がなくなりました。したがって、無限ループを使用できます。

while(true) {
   cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
   cin >> number;

   if(number < 0) break;

   // The rest of the code...
}

追加: コードに問題があります。偶数と奇数の数、および入力された数字の総数をユーザーに表示していません。

別の追加:より意味のある変数名を使用する必要があります。

int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;

もちろん、これらの名前に限定するつもりはありません。他の同様の名前を使用することもできます。

FOR THE INTEGER DIVISION PROBLEM : 式の値を適切な型 (この場合はfloat) にキャストする必要があります。また、平均変数のタイプをfloat次のように変更する必要があります。

float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
于 2012-10-29T00:38:36.837 に答える
0

cin >> number の直後で、< 0 をチェックし、そうであれば中断します。プログラムを 1 行ずつ実行して、実行の流れを感じてみてください。楽しく学び、頑張ってください!

于 2012-10-29T00:39:08.397 に答える