C 言語で特定の年月の日数を計算する方法
C言語では、関数を作成することで特定の年の特定の月の日数を計算できます。サンプルプログラムは以下の通りです。
#include <stdio.h>
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 1; // 是闰年
} else {
return 0; // 不是闰年
}
}
int getDaysInMonth(int year, int month) {
int days;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if (isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
break;
default:
days = -1; // 无效的月份
break;
}
return days;
}
int main() {
int year, month;
printf("请输入年份和月份(用空格隔开):");
scanf("%d %d", &year, &month);
int days = getDaysInMonth(year, month);
if (days == -1) {
printf("无效的月份!\n");
} else {
printf("%d年%d月的天数为:%d\n", year, month, days);
}
return 0;
}
上記の手順では、isLeapYear() 関数は特定の年がうるう年かどうかを判定し、getDaysInMonth() 関数は与えられた年と月に基づいて日数を計算します。プログラムはまずユーザー入力から年と月を取得し、それから getDaysInMonth() 関数を呼び出して日数を計算し、結果を表示します。