0
Follow
0
View

# c Language Leap Year Common Year Problem(1800~2800)

yewccz 注册会员
2023-02-27 12:37
); scanf ( "%d" , &year); // 1. 接收用户输入的年份 if (year < 0 || year > 3000 ) // 2. 检查年份是否在有效范围内 { ( "年份超出范围。\n" ); } else { if (year % 4 == 0 ) // 3. 检查能否被4整除 { if (year % 100 == 0 ) // 4. 检查能否被100整除 { if (year % 400 == 0 ) // 5. 检查能否被400整除 { flag = 1 ; } else { flag = 0 ; } } else { flag = 1 ; } } else { flag = 0 ; } if (flag) // 6. 根据flag的值判断是否为闰年 { printf ( "%d 是闰年。\n" , year); } else { printf ( "%d 不是闰年。\n" , year); } } return 0 ; } .
< !- - - - - >
dafanggua0807 注册会员
2023-02-27 12:37

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > here are the modified code:

``````#include

int main() {
int year, flag = 0;
printf("请输入年份：");
scanf("%d", &year);

if (year < 1800 || year > 2800) {
printf("年份超出范围。");
} else {
if (year % 4 == 0) {
if (year % 100 != 0) {
flag = 1;
} else {
if (year % 400 == 0) {
flag = 1;
}
}
}
if (flag) {
printf("%d 是闰年。\n", year);
} else {
printf("%d 不是闰年。\n", year);
}
}
return 0;
}

``````

Modification description:

1. joins input statement scanf("%d", & year); , read the year entered by the user.
2. Determines whether the year entered by the user is within the legal range.
3. Check whether it is divisible by 4. If yes, proceed to the next step. Otherwise the direct output is not leap year.
4. If it's divisible by 400, it's a leap year. Set flag to 1.
5. Otherwise it is not a leap year, set flag to 0.
6. If it is not divisible by 4, it is not a leap year. Set flag to 0.
7. Finally prints whether it is a leap year based on the value of flag.
duanshaoqing 注册会员
2023-02-27 12:37

Full C code implementation, using the if-else structure and scanf function to get the year the user entered:

``````#include

int main() {
int year, flag;
printf("请输入年份：");
scanf("%d", &year);
if (year < 1800 || year > 2800) {
printf("年份超出范围。");
} else {
if (year % 4 == 0) {
if (year % 100 != 0) {
flag = 1;
} else {
if (year % 400 == 0) {
flag = 1;
} else {
flag = 0;
}
}
} else {
flag = 0;
}
if (flag == 1) {
printf("%d 是闰年。\n", year);
} else {
printf("%d 不是闰年。\n", year);
}
}
return 0;
}

``````

1. Obtain the year entered by the user through the scanf function and store it in the year variable.
2. If the entered year is not in the range of 1800 to 2800, an error message is displayed, and the program ends.
3. If the year is divisible by 4, go to Step 4. Otherwise, go to Step 6.
4. If the year is divisible by 100, perform Step 5. Otherwise, it means leap year, flag = 1.
5. If the year is divisible by 400, it is a leap year, marked as flag = 1; Otherwise, it is not a leap year and flag = 0.
6. If the year is not divisible by 4, it is not a leap year and flag = 0.
7. Judge the result according to flag.

dxh6258 注册会员

Publish Time
2023-02-27 12:37
Update Time
2023-02-27 12:37