C++一个景区根据游人的年龄收取不同价格的门票。年龄小于等于10岁,门票免费,年龄在11岁到60岁之间,门票全价20元,年龄在60岁以上,门票半价10元。请编写游人类,根据年龄段决定能够购买的门票价格并输出。
时间: 2024-05-06 20:15:49 浏览: 15
好的,以下是一种实现方式:
```c++
#include <iostream>
using namespace std;
class Visitor {
public:
Visitor(int age) : age(age) {}
int getTicketPrice() const {
if (age <= 10) {
return 0;
} else if (age <= 60) {
return 20;
} else {
return 10;
}
}
private:
int age;
};
int main() {
int age;
cout << "请输入游客的年龄:";
cin >> age;
Visitor visitor(age);
cout << "门票价格为:" << visitor.getTicketPrice() << "元" << endl;
return 0;
}
```
我们定义了一个游人类 `Visitor`,它有一个年龄属性 `age` 和一个获取门票价格的方法 `getTicketPrice()`。在方法中,根据年龄段判断门票价格并返回。在 `main` 函数中,我们通过用户输入的年龄创建一个游人对象,并输出门票价格。
相关问题
某部门有10名职工,年龄相差均2岁,年龄最小的职工20岁,求年龄最大的职工的年龄,要求用C++递归函数实现
以下是用C++递归函数实现的代码:
```cpp
#include <iostream>
using namespace std;
int getMaxAge(int n) {
if(n == 1) {
return 20; // 最小年龄20岁
} else {
return getMaxAge(n-1) + 2; // 年龄相差2岁
}
}
int main() {
int n = 10;
cout << "年龄最大的职工的年龄为:" << getMaxAge(n) << endl;
return 0;
}
```
解释:
- getMaxAge是递归函数,参数n表示剩余的职工数量,返回值是当前职工的年龄。
- 当n=1时,递归结束,返回最小年龄20岁。
- 当n>1时,当前职工的年龄是前一个职工年龄加2岁。
- 在main函数中,n=10表示有10名职工,调用getMaxAge函数求得年龄最大的职工的年龄,并输出结果。
用C++编写程序:输入一个年龄,计算对应该年龄的出生年份并输出
好的,以下是用 C++ 编写的程序:
```c++
#include <iostream>
#include <ctime>
using namespace std;
int main() {
int age;
time_t t = time(nullptr); // 获取当前时间
tm* now = localtime(&t); // 将时间转换为本地时间
int currentYear = now->tm_year + 1900; // 获取当前的年份
cout << "请输入您的年龄:" << endl;
cin >> age;
int birthYear = currentYear - age;
cout << "您的出生年份是:" << birthYear << endl;
return 0;
}
```
程序首先获取当前时间,并计算出当前的年份。然后,程序通过输入的年龄,计算出对应的出生年份,并将其输出。注意,程序使用了 `localtime` 函数将时间转换为本地时间,因此需要包含 `<ctime>` 头文件。