[C Language Elementary] Use the function to find the leap year

If you want to find a leap year, you must first understand the rules of leap years:

Ordinary leap year : Gregorian calendar year isA multiple of 4, and not a multiple of 100, it is a leap year (such as 2004, 2020, etc. are leap years).
Century leap year : Gregorian calendar year isHundredsmust beMultiples of 400It is a leap year (for example, 1900 is not a leap year, but 2000 is a leap year).

With the judgment rule of leap year, it will be easier

The first is to construct the main function, and write out the location of the input, output and function:

#include <stdio.h>
int main()
{
    
    
	int a = 0;
	scanf("%d", &a);//输入xx年
	run_nian(a);//计算xx年之前的闰年的年份
	printf("%d", a);//显示xx年之前的闰年
	return 0;
}

Then construct the leap year judgment function run_nian:

The first step is to construct a for loop to judge each year from zero to the increment of the input value one by one.

(Because the default here is AD, a positive year, so you can also add an unsigned, unsigned integer to increase the range of years that can be judged)

int run_nian(a)
{
    
    
	int x;
	for (x = 0; x < a; x++) 
	{
    
    

		}
	}
}

The second step is to write out the two judgment conditions of leap year with if statement, namely:

if (x % 4 == 0 && x % 100 != 0)//年份为四的倍数,并且不是一百的倍数
		{
    
    
			printf("%-4d	", x);
		}
		if (x % 400 == 0)//年份为四百的倍数
		{
    
    
			printf("%-4d	", x);
		}

Enter 2000, the operation result is as follows (not fully shown):

insert image description here
Well, this is basically done, but the result is still a little unsightly. You can see that the last number of each line is wrapped, and one number is divided into two numbers. Although it can be adjusted by stretching the window, this is not what we want.

Then you can control the frequency of newlines by adding a variable count that prints newlines :

	for (x = 0; x < a; x++) 
	{
    
    
		if (x % 4 == 0 && x % 100 != 0)
		{
    
    
			printf("%-4d	", x);
			count = count++;
			if (count % 8 == 0)
			//每打印8个闰年就换一次行,即一行八个数字
				printf("\n");
		}
		if (x % 400 == 0)
		{
    
    
			printf("%-4d	", x);
			count = count++;
			if (count % 8 == 0)
				printf("\n");
		}

	}

When 2000 is input, the running results are as follows:
insert image description here
Of course, if you think that the years in each line are too few, you can also change the number of each line by changing the number 8 in the count line.

Written at the end
If this article is helpful to you, can you give me a little like ❤~ Your support is my biggest motivation.

The blogger is Xiaobai, with little talent and learning, and it is inevitable that there will be mistakes. Everyone is welcome to discuss and ask questions, and the blogger will correct it as soon as possible.

Thank you for watching hehe (๑•̀ㅂ•́)و✧~!

Guess you like

Origin blog.csdn.net/weixin_70218204/article/details/127135646