柜台不工作?

时间:2013-03-20 18:15:06

标签: c++

我正在为家庭作业编写一个程序,根据品牌,租用天数和行驶里程来计算租车费率。总体而言,该程序工作,除了当提示用户计算要计算的汽车数量时,程序在超过该数量之后继续提示用户输入。此外,里程的格式对于输入的第一辆车是正确的,但随后的输入会发生变化。

非常感谢对这两个问题的任何帮助!

代码:

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

2 个答案:

答案 0 :(得分: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),则第三次迭代结束时的条件将为false,我们已经结束

答案 1 :(得分:1)

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

while(counter < cars)

而不是

while(counter <= cars)
相关问题