我必须创建一个程序来计算机票费用。到目前为止这是一个简单的程序,我还没有完成添加,但每次运行它时结果都是 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;
}
最佳答案
您的困惑是完全可以理解的——您遗漏的一点是,当您分配一个变量时,您是在 那个时刻 将左侧分配给右侧的结果。它不像代数,你说 f(x) = x + 5
而 f(x)
总是 x + 5
是什么。
因此,当 distance
为 0
(您刚刚初始化)时,您分配 double distance_price = distance * 0.15
。 distance_price
仍然是 0
,即使在您要求输入并更改 distance
之后也是如此。
在请求输入后进行价格计算,一切都会正常进行。
关于C++机票费用计算项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890183/