2012-09-20 126 views
0

我刚刚学习C++,我需要这个程序来为班级工作。从逻辑上讲,它工作。我使用的是bloodshed.net的IDE ...它似乎只是忽略了cin >> kwh;。我认为它的流血事件是错误的,不是我的,但我可能会犯错。C++我的逻辑有什么问题?

下面的代码:

#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"); 


} 
+5

代码中没有'cin << kwh;';我假设你的意思是第二个'cin >> kwh;'? – user9876

+0

它适用于我的情况与IDE代码:块删除'系统(“暂停”);' – nKandel

+0

没什么。必须是您正在使用的编译器。 –

回答

-1

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

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

+0

学会在这里写出温柔的英语。不要过度使用快捷方式,检查语法,格式清晰,回答紧凑。不要表现得像个孩子,即使你是一个孩子。这是写在这里的权利,不是正确的。尝试赢得它。 –

3

如果kwh < 0,则在该循环的实例中从不计算monthCost。因此,它将使用monthCost在循环的前一个实例中的任何值,或者如果这是循环的第一次执行,它将为零。所以当你说节目忽略了你的千瓦时价值时,你是对的。在你获得价值后,你不会对它做任何事情。