C language beginners exercises (1)

1: Determine whether it is a leap year

Problem-solving ideas: First of all, you must know how to judge leap year before you can do this question. If it is divisible by 4 and not divisible by 100, or it can be divisible by 400, if one of them is satisfied, it is a leap year.

The following is my personal solution to the problem. The answer is not unique and is for reference only.

#include "stdio.h"
int main()
{
	int year = 0;
	scanf("%d", &year);
	if ((year % 4 == 0 )&& (year % 100 != 0) ||( year % 400 == 0))
	{
		printf("%d是闰年", year);
	}
	else
	{
		printf("%d不是是闰年", year);
	}
	return 0;
}

2: Calculate the number of occurrences of 9 between 1-100

Problem-solving ideas: 9 can be in the ones place or in the tens place, so two situations need to be judged. The following answers are not exclusive and are for reference only.

#include "stdio.h"
int main()
{
	int a = 0;
	int count = 0;
	for (a = 1; a <= 100; a++)
	{
		if (a % 10 == 9)//计算各位上的9的个数
			count++;
		if (a / 10 == 9)//计算十位上的9的个数
			count++;
	}
	printf("count = %d", count);
	return 0;
}

3: Score sum: 1-1/2+1/3-1/4+1/5+...+1/99-1/100

Problem-solving idea: Observe carefully and find that each of them is added and subtracted, so there can be an intermediate variable, and the symbol is changed during calculation. Another thing to note is that the int type can no longer be used when summing.

The following answers are not exclusive and are for reference only.

#include "stdio.h"
int main()
{
	int i = 0;
	float sum = 0;
	int flag = 1;
	for (i = 1; i <= 100; i++)
	{
		sum += flag * 1.0 / i;
		flag = -flag;//加减加减..
	}
	printf("%f\n", sum);
	return 0;
}

4: Print the prime numbers between 100-200:

Problem-solving ideas: First of all, we must know what a prime number is: a prime number that can only be divisible by 1 and itself is called a prime number, that is, any number between 2 and i-1 that cannot be divisible by itself is a prime number. The following answers are not exclusive and are for reference only.

#include "stdio.h"
int main()
{
	int i = 0;
	int count = 0;
	for (i = 100; i <= 200; i++)
	{
		int j = 0;
	    for (j = 2; j < i; j++)
		{
		if (i % j == 0)
			{
				break;
			}
	     }
		//当i在2到i-1都不能被j整除时,此时j==i
		if (j == i)
		{
			count++;
			printf("%d ", i);
		}
    }
} 
		

There is another small detail: all even numbers are not prime numbers, so this question can still be optimized. There are more ideas for solving this question, leave it to everyone to think for themselves~

#include "stdio.h"
int main()
{
	int i = 0;
	int count = 0;
	for (i = 101; i <= 200; i+=2)
	{
		int j = 0;
	    for (j = 2; j < i; j++)
		{
		if (i % j == 0)
			{
				break;
			}
	     }
		//当i在2到i-1都不能被j整除时,此时j==i
		if (j == i)
		{
			count++;
			printf("%d ", i);
		}
    }
} 
	

Guess you like

Origin blog.csdn.net/qq_69424518/article/details/126423722