C ++根据年龄计算票价,然后将它们相加

时间:2014-09-09 13:34:15

标签: c++

我必须制作一个非常简单的程序,询问用户他/她想要购买多少张票。然后它会询问每张门票的年龄。然后它应该能够使用这些价格计算门票的总成本:

  • 如果拥有者超过15岁,则票价为80。
  • 否则,如果拥有者至少8岁,那么他支付30。
  • 8岁以下的儿童可以免费获得门票。

我的问题是如何计算门票的总价?

这就是我走了多远:

我使用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;
}

1 个答案:

答案 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;
}