C ++机票费用计算项目

时间:2015-08-08 06:04:31

标签: c++

我必须创建一个程序来计算机票费用。到目前为止这是一个简单的程序,我没有添加它,但每次运行它时结果都是0.我的代码中是否缺少某些东西?我是初学者,我很感激有关改进我的代码的任何建议。谢谢。

#include <iostream>
            using namespace std;

            void main () {

                int distance = 0;
                int num_bags= 0;
                int num_meals= 0;
                double distance_price = distance * 0.15;
                double bag_price = num_bags * 25.00;
                double meal_price = num_meals * 10.00;
                double total_airfare = 0.00;


            cout << "CorsairAir Fare Calculator" << endl;

            cout << "Enter the distance being travelled:  " << endl;
            cin >> distance;

            cout << "Enter number of bags checked:  " <<endl;
            cin >> num_bags;


            cout << "Enter the number of meals ordered:  " << endl;
            cin >> num_meals;


            total_airfare = (distance_price + bag_price + meal_price);


            cout << total_airfare;




            }

2 个答案:

答案 0 :(得分:2)

你的困惑是完全可以理解的 - 你遗失的部分是,当你指定一个变量时,你会在那个时刻将左侧分配给右侧的结果。它不像代数,你说f(x) = x + 5f(x)总是x + 5

因此,当double distance_price = distance * 0.15distance(您刚刚初始化)时,请指定0。在您要求输入并更改distance_price后,0仍然是distance

在您要求输入后进行价格计算,一切都会正常工作。

答案 1 :(得分:1)

您正在计算distance_price bag_price meal_price的默认值,例如0,而不是您从用户那里获得的值。

下面的代码工作正常,你不会看到问题。

   #include <iostream>
    using namespace std;
    // My compiler did not allow void main so used int main
    int main () {

    int distance = 0;
    int num_bags= 0;
    int num_meals= 0;

    double distance_price ;
    double bag_price ;
    double meal_price;
    double total_airfare;

    cout << "CorsairAir Fare Calculator" << endl;

    cout << "Enter the distance being travelled:  " << endl;
    cin >> distance;

    cout << "Enter number of bags checked:  " <<endl;
    cin >> num_bags;


    cout << "Enter the number of meals ordered:  " << endl;
    cin >> num_meals;


    distance_price = distance * 0.15;
    bag_price = num_bags * 25.00;
    meal_price = num_meals * 10.00;
    total_airfare = 0.00;


    total_airfare = distance_price + bag_price + meal_price;


    cout << total_airfare;
    return 0;
    }

<强>结果

CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100