0

私はちょうど C++ を学んでおり、このプログラムがクラスで機能する必要があります。論理的には機能します。私はbloodshed.netのIDEを使用しています...そして..を無視しているようcin >> kwh;です. 私のせいではなく、流血のせいだと思いますが、私が間違っている可能性があります。

ここにコード:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{

    double kwh = -1, monthCost = 0, totalCost = 0;
    int monthCount = 0;
    bool nextMonth = 0;

    do
    {  
       kwh = -1;
       cout << "How many KWH did you use month " << ++monthCount << "?\n";
       cin >> kwh;

       if (kwh <= 1000 && kwh >= 0)
       {
               monthCost = kwh * 0.6;
       }

       else if (kwh < 0)
       {      
            cout << "\nInvalid number of KWH.";
            while (kwh < 0)
            {
                  cout << "How many KWH did you use month " << monthCount 
                          << "?\n";
                  // Could you tell me what I'm doing wrong? I honestly think its
                  // the programs fault, not mine. Driectly below this comment
                  // I'm asking the user for the KWH and it just ignores it
                  // when I compile and run. WHY?!?
                  cin >> kwh;
            }
       }

       else if (kwh > 1000)
       {
            monthCost = ((kwh - 1000) * 0.45) + 600;
       }


       totalCost += monthCost;
       cout << "\nYour electric bill for this month " << monthCount << " is $"
               << monthCost << ".\n";

       cout << "Would you like to enter another month? (1/0)\n";
       cin >> nextMonth;
       cout << "\n";
   }
   while (nextMonth == 1);

   cout << "\n\nYour total for all " << nextMonth << " month(s) is %"
           << totalCost << ".\n";
   system("pause");


}
4

2 に答える 2

3

の場合kwh < 0、そのループのインスタンスで monthCost が計算されることはありません。その結果、ループの前のインスタンスで monthCost が持っていた値を使用するか、ループが初めて実行された場合はゼロになります。したがって、プログラムが kwh の値を無視していると言うとき、あなたは正しいです。値を取得した後は、何もしません。

于 2012-09-20T19:53:48.277 に答える
-1

cin << kwh;あなたのコードにはありません。それらだけがありcin >> kwh;ます。

流血については何も知りませんが、kwhを整数として定義し、コンパイラがコマンドラインからの文字列入力を受け入れないためでしょうか?

于 2012-09-20T19:52:00.560 に答える