2013-03-20 83 views
0

我正在编写一个家庭作业计划,该计划可根据品牌,租用日期和行驶里程计算出租汽车价格。整体而言,该程序除了在用户被提示要计算的汽车数量时起作用外,该程序在数字超过后继续提示用户输入。另外,对于输入的第一辆车而言,英里的格式是正确的,但随后的输入会改变。计数器不工作?

任何与这两个问题的帮助将不胜感激!

代码:

#include <iostream> 
#include <string> 
#include <sstream> 
#include <iomanip> 
#include <cmath> 

using namespace std; 

int main() 
{ 
    // Change the console's background color. 
    system ("color F0"); 

    // Declare the variables. 
    char carType; 
    string brand, f("Ford"), c("Chevrolet"); 
    int counter = 0, cars = 0; 
    double days, miles, cost_Day, cost_Miles, day_Total; 

    cout << "Enter the number of cars you wish to enter: "; 
    cin >> cars; 
    cin.ignore(); 

    while (counter <= cars) 
    { 

     cout << "Enter the car type (F or C): "; 
     cin >> carType; 
     cin.ignore(); 
     cout << "Enter the number of days rented: "; 
     cin >> days; 
     cin.ignore(); 
     cout << "Enter the number of miles driven: "; 
     cin >> miles; 
     cin.ignore(); 


     if (carType == 'F' || carType == 'f') 
     { 
      cost_Day = days * 40; 
      cost_Miles = miles * .35; 
      day_Total = cost_Miles + cost_Day; 
      brand = f; 
     } 
     else 
     { 
      cost_Day = days * 35; 
      cost_Miles = miles * .29; 
      day_Total = cost_Miles + cost_Day; 
      brand = c; 
     } 

     cout << "\nCar   Days Miles  Cost\n"; 
     cout << left << setw(12) << brand << right << setw(6) << days << right << setw(8) << miles 
     << fixed << showpoint << setprecision (2) << setw(8) << right << "$" << day_Total << "\n\n"; 
     counter++; 
    } 


     system ("pause"); 
} 
+1

考虑'而(计数器<汽车)'对于初学者。虽然老实说,我只会'(汽车){... - 汽车; }' – WhozCraig 2013-03-20 18:17:29

+0

int counter = 0,cars = 0;在//声明变量。 – 2013-03-20 18:17:41

+0

@WhozCraig如果我这样做,它会不会停止一个迭代短的用户规定的车辆数量进入? – 2013-03-20 18:18:52

回答

3

您已经开始从0 int counter = 0, cars = 0;

计数然后你算,直到你等于已输入的号码(“等于”的while (counter <= cars)位)。

作为工作例子,如果我想3项:

Start: counter = 0, cars = 3. 
0 <= 3: true 
End of first iteration: counter = 1 
1 <= 3: true 
End of second iteration: counter = 2 
2 <= 3: true 
End of third iteration: counter = 3 
3 <= 3: true (the "or equal" part of this) 
End of FORTH iteration: counter = 4 
4 <= 3: false -> Stop 

我们已经完成了4次迭代,而不是3。如果我们只在最后检查“严格小于”(counter < cars),条件第三次迭代将是错误的,我们已经结束了。

1

while循环的标题应该是:

while(counter < cars) 

而不是

while(counter <= cars)