写一段代码输入年份输出对应的天干地支
时间: 2024-02-23 15:03:06 浏览: 234
下面是一段C++代码,可以根据输入的年份计算出对应的天干地支:
```c++
#include <iostream>
using namespace std;
const string heavenlyStems[] = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
const string earthlyBranches[] = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
int main() {
int year;
cout << "请输入年份:" << endl;
cin >> year;
string heavenlyStem = heavenlyStems[(year - 4) % 10];
string earthlyBranch = earthlyBranches[(year - 4) % 12];
cout << "对应的天干地支为:" << heavenlyStem << earthlyBranch << endl;
return 0;
}
```
这段代码的思路是根据输入的年份,计算出对应的天干地支。具体实现中使用了一个字符串数组,保存了天干地支的名称,根据输入的年份和数组中的数据,可以计算出对应的天干地支。最后输出对应的天干地支名称。
相关问题
写一段java程序来计算日天干地支
下面是一个Java程序示例,可以根据输入的日期计算出对应的日天干地支:
```java
import java.time.LocalDate;
public class TianganDizhi {
private static final String[] tiangan = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
private static final String[] dizhi = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
public static String getTiangan(LocalDate day) {
int offset = (day.getYear() - 4) % 60;
return tiangan[offset % 10];
}
public static String getDizhi(LocalDate day) {
int offset = (day.getYear() - 4) % 60;
return dizhi[offset % 12];
}
public static String getTianganDizhi(LocalDate day) {
String tiangan = getTiangan(day);
String dizhi = getDizhi(day);
int offset = (day.getDayOfMonth() - 1) % 60;
String tianganDay = tiangan.charAt(offset % 10) + "";
String dizhiDay = dizhi.charAt(offset % 12) + "";
return tianganDay + dizhiDay;
}
public static void main(String[] args) {
LocalDate day = LocalDate.of(2022, 2, 8);
String tianganDizhi = getTianganDizhi(day);
System.out.printf("%s 的日天干地支为:%s", day, tianganDizhi);
}
}
```
程序的思路和Python程序类似,只是Java代码需要使用Java 8中新增的日期时间API来处理日期。程序先计算出对应年份的天干和地支,然后计算出对应日期的日天干和地支,最后将天干和地支合并起来即可得到日天干地支。
写一段程序来计算日天干地支
下面是一个Python程序示例,可以根据输入的日期计算出对应的日天干地支:
```python
import datetime
tiangan = "甲乙丙丁戊己庚辛壬癸"
dizhi = "子丑寅卯辰巳午未申酉戌亥"
def get_tiangan(day):
offset = (day.year - 4) % 60
return tiangan[offset % 10]
def get_dizhi(day):
offset = (day.year - 4) % 60
return dizhi[offset % 12]
def get_tiangan_dizhi(day):
tiangan = get_tiangan(day)
dizhi = get_dizhi(day)
offset = (day.day - 1) % 60
tiangan_day = tiangan[offset % 10]
dizhi_day = dizhi[offset % 12]
return tiangan_day + dizhi_day
# 测试程序
day = datetime.date(2022, 2, 8)
tiangan_dizhi = get_tiangan_dizhi(day)
print(f"{day} 的日天干地支为:{tiangan_dizhi}")
```
程序的核心思路是根据输入的日期先计算出对应的年份的天干和地支,然后根据日期计算出对应的日天干和地支。最后将天干和地支合并起来即可得到日天干地支。
阅读全文