用c语言定义一个函数,输入年份可得此年每个月的天数,用空格隔开
时间: 2024-05-04 20:17:17 浏览: 10
好的,以下是用C语言定义的函数,可以输入年份并返回此年每个月的天数,以空格隔开:
```c
#include <stdio.h>
// 判断是否为闰年
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 1;
} else {
return 0;
}
}
// 获取每个月的天数
void getMonthDays(int year, int days[]) {
for (int i = 1; i <= 12; i++) {
if (i == 2) {
if (isLeapYear(year)) {
days[i] = 29;
} else {
days[i] = 28;
}
} else if (i == 4 || i == 6 || i == 9 || i == 11) {
days[i] = 30;
} else {
days[i] = 31;
}
}
}
// 主函数
int main() {
int year;
int days[13]; // 数组下标从1开始,需要多一个元素
printf("请输入年份:");
scanf("%d", &year);
getMonthDays(year, days);
printf("%d年的每个月的天数为:", year);
for (int i = 1; i <= 12; i++) {
printf("%d ", days[i]);
}
printf("\n");
return 0;
}
```
使用方法:
1. 将上述代码保存为一个以`.c`为后缀的文件,比如`count_days.c`。
2. 在命令行中进入该文件所在的目录,执行`gcc count_days.c -o count_days`编译生成可执行文件。
3. 执行`./count_days`运行程序,按照提示输入年份即可。