2013-03-20 84 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)