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 值,或者如果这是第一次执行循环,它将为零。因此,当您说该程序忽略了您的千瓦时价值时,您是对的;获得价值后,您不会对它做任何事情。

于 2012-09-20T19:53:48.277 回答
-1

您的代码中没有cin << kwh;。只有那些cin >> kwh;

我对流血事件一无所知,但也许是因为您将 kwh 定义为整数,而编译器不接受从命令行输入的字符串?

于 2012-09-20T19:52:00.560 回答