PTA用C语言求月天数
时间: 2024-12-18 11:13:20 浏览: 70
在C语言中,计算每个月的天数通常需要考虑是否是闰年,并使用相应规则。这里可以编写一个简单的函数来完成这个任务,例如利用"蔡勒公式"(Zeller's congruence),它可以根据公历日期快速判断是否为闰年:
```c
#include <stdio.h>
// 函数声明,输入年份、月份(1-12)、日,返回该月天数
int getMonthDays(int year, int month, int day);
// 蔡勒公式判断是否为闰年
int isLeapYear(int year) {
if (year % 400 == 0) return 1; // 世纪闰年
else if (year % 100 == 0) return 0; // 非世纪非闰年
else if (year % 4 == 0) return 1; // 普通闰年
else return 0;
}
// 根据月份数量计算天数
int getMonthDays(int year, int month, int day) {
static const int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 如果是闰年,2月增加一天
if (isLeapYear(year) && month == 2)
return days_in_month[month] + 1;
else
return days_in_month[month];
}
int main() {
int year, month, day;
printf("请输入年份、月份和日份:");
scanf("%d %d %d", &year, &month, &day);
printf("该月共有%d天。\n", getMonthDays(year, month, day));
return 0;
}
```
当你运行这个程序并输入具体的年、月、日,它会输出对应的月天数。注意,此代码假设输入的日期有效,实际应用中可能需要添加更多的错误检查。
阅读全文
相关推荐


















