C++根据年龄计算票价,然后求和

C++ Calculating ticket prices based on age, then summing them

本文关键字:然后 求和 计算 C++      更新时间:2023-10-16

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

  • 如果车主年龄超过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;
}

使用当前语句price + total_price;,您将一事无成。将其更改为total_price += price;,您将开始在while-循环的每次迭代中将price添加到total_price

#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;
}