Ubuntu 用C语言输入一个年份月份,判断该年该月由多少天;(要求封装+传参调用);
时间: 2024-01-29 08:04:21 浏览: 53
以下是一个简单的C语言函数,可以用来计算给定年份月份的天数:
```c
#include <stdio.h>
int days_in_month(int year, int month) {
int is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
int days = 0;
switch (month) {
case 1:
days = 31;
break;
case 2:
days = is_leap ? 29 : 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
printf("Invalid month: %d\n", month);
break;
}
return days;
}
int main() {
int year, month;
printf("Enter year: ");
scanf("%d", &year);
printf("Enter month: ");
scanf("%d", &month);
int days = days_in_month(year, month);
printf("There are %d days in %d/%d.\n", days, year, month);
return 0;
}
```
你可以在需要计算天数的地方调用 `days_in_month` 函数,并传入年份和月份作为参数。例如:
```c
int days = days_in_month(2021, 3);
printf("There are %d days in March 2021.\n", days);
```
输出结果为:
```
There are 31 days in March 2021.
```
阅读全文