c++编写一个程序,判断年份的生肖
时间: 2024-10-09 13:09:19 浏览: 31
在C++中,我们可以创建一个函数来计算给定年份的生肖。中国传统的十二生肖按照12年的周期轮回,下面是基于公历的简单算法:
```cpp
#include <iostream>
enum class ChineseZodiac {
Rat,
Ox,
Tiger,
Rabbit,
Dragon,
Snake,
Horse,
Goat,
Monkey,
Rooster,
Dog,
Pig
};
ChineseZodiac getChineseZodiac(int year) {
const int zodiacYears[] = {4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48};
int index = (year - 1900) % 12;
if (index < 0)
index += 12;
return static_cast<ChineseZodiac>(zodiacYears[index]);
}
int main() {
int year;
std::cout << "Enter a year: ";
std::cin >> year;
ChineseZodiac zodiac = getChineseZodiac(year);
switch (zodiac) {
case ChineseZodiac::Rat:
std::cout << "That year is the Year of the Rat.\n";
break;
// 其他生肖依次添加...
default:
std::cout << "Invalid year or unknown生肖.\n";
}
return 0;
}
```
这个程序首先定义了一个枚举类`ChineseZodiac`表示十二生肖,然后通过计算年份与生肖周期的余数来确定生肖。在`main`函数中,用户输入年份后,程序调用`getChineseZodiac`函数获取生肖并打印。
阅读全文