首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++机票费计算方案

C++机票费计算方案
EN

Stack Overflow用户
提问于 2015-08-08 14:04:31
回答 2查看 142关注 0票数 1

我必须创建一个计算机票费用的程序。到目前为止,这是一个简单的程序,我还没有完成对它的添加,但每次我运行它时,结果都是0。我的代码中是否遗漏了什么?我是一个初学者,我将感谢任何关于改进我的代码的建议。谢谢。

代码语言:javascript
复制
#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;




            }
EN

回答 2

Stack Overflow用户

发布于 2015-08-08 14:08:10

你的困惑是完全可以理解的--你遗漏的一点是,当你赋值一个变量时,你在那个时刻将左边赋值给右边的结果。这不像代数,你说f(x) = x + 5f(x)总是x + 5是什么。

因此,当distance0 (您刚刚初始化了它)时,您可以指定double distance_price = distance * 0.15。即使在您请求输入并更改distance之后,distance_price仍然是0

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

票数 2
EN

Stack Overflow用户

发布于 2015-08-08 17:57:00

您正在使用默认值(即0 )计算distance_price bag_price meal_price,而不是使用您从user获取的值。

下面的代码运行良好,你不会看到这个问题。

代码语言:javascript
复制
   #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;
    }

结果

代码语言:javascript
复制
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31890183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档