思路:判断闰年的标准是:能整除4且不能整除100 或者能整除400
#include<stdio.h>
#include<math.h>
int main()
{
int year = 0;
int count = 0;
printf("1000-2000年之间的素数有: ");
for (year = 1000; year <= 2000; year++)
{
if (year % 100== 0 )
{
if (year % 400 == 0)
{
printf("%d ", year);
count++;
}
}
else if (year % 4 == 0)
{
printf("%d ", year);
count++;
}
}
printf("\n共有%d个闰年\n", count);
system("pause");
return 0;
}
进阶篇
直接将if语句优化
#include<stdio.h>
#include<math.h>
int main()
{
int year = 0;
int count = 0;
printf("1000-2000年之间的素数有: ");
for (year = 1000; year <= 2000; year++)
{
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
printf("%d ", year);
count++;
}
}
printf("\n共有%d个闰年\n",count);
system("pause");
return 0;
}
运行结果如下:
实现一个函数判断year是不是闰年
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int judgeLeapYear(int year)
{
if((year % 4 == 0 && year %100 != 0) || (year% 400 == 0))
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int year;
int ret= 0;
printf("请输入年份:");
scanf("%d", &year);
ret = judgeLeapYear(year);
if(ret == 1)
{
printf("%d年是闰年\n", year);
}
else
{
printf("%d年非闰年\n", year);
}
system("pause");
return 0;
}
运行结果如下: