我必须制作一个非常简单的程序,询问用户他/她想要购买多少张票。然后它会询问每张门票的年龄。然后它应该能够使用这些价格计算门票的总成本:
我的问题是如何计算门票的总价?
这就是我走了多远:
我使用while循环让用户输入多个年龄段 以及为不同年龄分配价格的if语句。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int age, tickets, persons, price, total_price;
persons = 1, total_price = 0;
cout << "How many tickets do you want? ";
cin >> tickets;
cout << "Number of tickets: " << tickets << endl;
while (tickets >= persons) {
cout << "Enter age for person " << persons << ": ";
cin >> age;
{
if (age > 15)
price = 80;
else if (age < 8)
price = 0;
else
price = 30;
}
price + total_price;
persons++;
}
cout << "Total price is: " << total_price;
return 0;
}
答案 0 :(得分:1)
使用当前语句price + total_price;
,您什么都不做。将其更改为total_price += price;
,您将在price
- 循环的每次迭代中开始将total_price
添加到while
。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int age, tickets, persons, price, total_price;
persons = 1, total_price = 0;
cout << "How many tickets do you want? ";
cin >> tickets;
cout << "Number of tickets: " << tickets << endl;
while (tickets >= persons) {
cout << "Enter age for person " << persons << ": ";
cin >> age;
{
if (age > 15)
price = 80;
else if (age < 8)
price = 0;
else
price = 30;
}
total_price += price;
persons++;
}
cout << "Total price is: " << total_price;
return 0;
}