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");
}
4

2 回答 2

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),第三次迭代结束时的条件将是错误的,我们会在那里结束。

于 2013-03-20T18:24:58.267 回答
1

您的 while 循环的标题应该是:

while(counter < cars)

而不是

while(counter <= cars)
于 2013-03-20T18:25:08.000 回答