C 練習例4
問題:年・月・日を入力し、その日がその年の何日目かを判定します。
プログラム分析:3月5日を例にすると、まず最初の2か月の日数を合計し、それに5日を加えるとその年の何日目かがわかります。特殊なケースとして、閏年で入力した月が3より大きい場合は、1日多く加える必要があります。
例
#include <stdio.h>
int isLeapYear(int year) {
// 閏年の判定ルール:4で割り切れ、かつ(100で割り切れない、または400で割り切れる)
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1;
}
return 0;
}
int main() {
int year, month, day;
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int totalDays = 0;
printf("年、月、日を入力してください(形式:年 月 日):");
scanf("%d %d %d", &year, &month, &day);
// 閏年かどうかを判定
if (isLeapYear(year)) {
daysInMonth[1] = 29; // 閏年の2月は29日ある
}
// 1月1日から入力された日付までの日数を計算
for (int i = 0; i < month - 1; i++) {
totalDays += daysInMonth[i];
}
totalDays += day; // 入力された月の日数を加える
printf("%d年%d月%d日はその年の第%d日目です\n", year, month, day, totalDays);
return 0;
}
上記の例の出力結果:
请输入年份、月份和日期(格式:年 月 日):2024 3 5 2024年3月5日是该年的第65天
最適化して、日付の判定を追加します:
例
#include <stdio.h>
int isLeapYear(int year) {
// 閏年の判定ルール:4で割り切れ、かつ(100で割り切れない、または400で割り切れる)
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1;
}
return 0;
}
int main() {
int year, month, day;
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
printf("年、月、日を入力してください(形式:年 月 日):");
if (scanf("%d %d %d", &year, &month, &day) != 3) {
printf("入力が無効です。正しい年、月、日を入力してください。\n");
return 1;
}
// 年が有効かどうかをチェック
if (year <= 0) {
printf("年が無効です。正の整数を入力してください。\n");
return 1;
}
// 月が有効かどうかをチェック
if (month < 1 || month > 12) {
printf("月が無効です。1から12の間の数字を入力してください。\n");
return 1;
}
// 日が有効かどうかをチェック
if (isLeapYear(year)) {
daysInMonth[1] = 29; // 閏年の2月は29日ある
}
if (day < 1 || day > daysInMonth[month - 1]) {
printf("日が無効です。有効な日付を入力してください。\n");
return 1;
}
// 1月1日から入力された日付までの日数を計算
int totalDays = 0;
for (int i = 0; i < month - 1; i++) {
totalDays += daysInMonth[i];
}
totalDays += day; // 入力された月の日数を加える
printf("%d年%d月%d日はその年の第%d日目です\n", year, month, day, totalDays);
return 0;
}
上記の例の出力結果:
请输入年份、月份和日期(格式:年 月 日):2024 2 32 日期不合法,请输入有效的日期。その他の拡張