C语言实战:计算21世纪指定年份前的所有闰年
C语言实战:计算21世纪指定年份前的所有闰年
这篇文章将带你学习如何使用C语言编写程序,查找并输出21世纪指定年份前的所有闰年。
闰年的判断规则:
- 能被4整除但不能被100整除的年份是闰年。* 能被400整除的年份是闰年。
**程序代码:**c#include <stdio.h>
void printLeapYears(int year) { if (year < 2000 || year > 2099) { printf('Invalid year! '); } else { int startYear = 2000; int endYear = year; int foundLeapYear = 0; for (int i = startYear; i <= endYear; i++) { if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) { printf('%d ', i); foundLeapYear = 1; } } if (!foundLeapYear) { printf('None '); } }}
int main() { int year; printf('请输入21世纪的一个年份:'); scanf('%d', &year); printLeapYears(year); return 0;}
代码解释:
-
printLeapYears函数: - 接受一个年份作为参数 (year)。 - 检查输入年份是否在21世纪范围内 (2000-2099)。 - 使用循环遍历从2000年到输入年份之间的所有年份。 - 根据闰年规则判断当前年份是否为闰年。 - 如果是闰年,则打印该年份。 - 使用foundLeapYear变量标记是否找到了闰年。 - 如果没有找到任何闰年,则输出 'None'。 -
main函数: - 从用户处获取一个年份。 - 调用printLeapYears函数来打印该年份之前的闰年。
示例:
输入:
2023
输出:
200020042008201220162020
总结:
这篇文章介绍了如何使用C语言编写程序计算21世纪指定年份前的所有闰年。程序简单易懂,并包含详细的代码解释和示例,希望对你有所帮助。
原文地址: https://www.cveoy.top/t/topic/clik 著作权归作者所有。请勿转载和采集!