c++输入某年某月某日,判断这一天是这一年的第几天。函数fun的功能是,返回某天是这一年的第几天 点击复制后,将打开C知道体验页
时间: 2023-06-17 21:04:21 浏览: 140
以下是实现代码:
#include <iostream>
using namespace std;
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
int fun(int year, int month, int day) {
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days = 0;
for (int i = 0; i < month - 1; i++) {
days += daysInMonth[i];
if (i == 1 && isLeapYear(year)) {
days++;
}
}
days += day;
return days;
}
int main() {
int year, month, day;
cout << "请输入年份:";
cin >> year;
cout << "请输入月份:";
cin >> month;
cout << "请输入日期:";
cin >> day;
cout << year << "年" << month << "月" << day << "日是这一年的第" << fun(year, month, day) << "天" << endl;
return 0;
}
代码思路:
- 定义一个函数
isLeapYear
,判断某年是否是闰年。闰年的判断方法是:能被4整除但不能被100整除,或者能被400整除。 - 定义函数
fun
,根据输入的年份、月份和日期,计算出这一天是这一年的第几天。- 定义一个数组
daysInMonth
,存储每个月的天数,注意二月份要判断是否是闰年。 - 用一个循环,计算出输入的日期之前的所有天数,然后再加上输入的日期。
- 定义一个数组
- 在主函数中,先输入年份、月份和日期,然后调用函数
fun
计算出这一天是这一年的第几天,最后输出结果。
注意:这段代码适用于公历日期的计算,对于其他历法(比如农历),需要使用不同的计算方法。
相关推荐

















