[C Language] 100 Computer Test Questions and Code Answers (Part 1)

1. Topic: Classical problem: There is a pair of rabbits. They give birth to a pair of rabbits every month from the third month after birth. After the rabbit grows to the third month, they give birth to a pair of rabbits every month. If the rabbits do not die, , what is the total number of rabbits per month? (20 months before export)

  • Analysis: The rabbit's pattern is the sequence 1,1,2,3,5,8,13,21...that is, the next month is the sum of the previous two months. This model is called the fibonacci sequence in mathematics.
    Insert image description here
  • Code:
#include <stdio.h>

int fib(int n) {
    
    
	if (n == 1 || n == 2) {
    
    
		return 1;
	}else{
    
    
		return fib(n - 1) + fib(n - 2);
	}
}

int main()
{
    
    
	for (int i = 1; i <= 20; i++) {
    
    
		printf("第%d个月兔子总数为:%d\n", i, fib(i));
	}
	return 0;
}

Insert image description here

2. Question: Determine how many prime numbers there are between 101-200, and output all prime numbers.

  • What are prime numbers? The so-called prime number is what we usually call a prime number. It can only be divided by 1 and itself, that is, a natural number that has no other factors except 1 and itself .
  • Suppose we ask whether the number 7 is a prime number. We need to use 2 3 4 5 6 to divide it, so the trial division range is 2~i-1.
  • Code:
#include <stdio.h>
int main()
{
    
    
	int i=0;
	int count = 0; //素数个数
	
	for (i = 101; i <= 200; i++) {
    
    
		int j = 0;
		int flag = 1; //假设是素数
		for (j = 2; j < i; j++) {
    
     // i是否是素数,拿2 到 i-1 范围的数去试除
			if (i % j == 0) {
    
    
				flag = 0;
				break; //不是素数,跳出此循环
			}		
		}
		if (flag == 1) {
    
    
			printf("%d\t", i);
			count++;
		}
	}
	printf("素数的个数为%d", count);
	return 0;
}

Insert image description here

3. Question: Print out all the "narcissus numbers". The so-called "narcissus number" refers to a three-digit number whose cube sum is equal to the number itself.

  • analyze:
    • For example, 153 is the "daffodil number" because: 153 = 1 to the third power + 5 to the third power + 3 to the third power.
    • Use a for loop to control 100-999 numbers, and decompose each number into units, tens, and hundreds.
  • Code:
#include <stdio.h>
int main()
{
    
    
	int i = 0;

	for (i = 100; i <= 999; i++) {
    
    
		int a = i % 10; //个位
		int b = (i / 10) % 10; //十位
		int c = i / 100; //百位
		if (a * a * a + b * b * b + c * c * c == i) {
    
    
			printf("%d\t", i);
		}
	}
	return 0;
}

Insert image description here

4. Question: Decompose a positive integer into prime factors. For example: input 90, print out 90=2 *3 * 3 *5.

  • Analysis: The idea of ​​decomposing prime factors is to continuously divide the number n by an increasing number i (the number is initially 2 and increases to n) . If i can be divided evenly, then the current i will be one of the factors of n , and then n Use this factor to reduce, that is, n = n / i, and then repeat the above operation. If n = i, it means that the decomposition of factors is over .
  • Code:
#include <stdio.h>
int main()
{
    
    
	int n;
	printf("请输入一个正整数:");
	scanf("%d", &n);
	printf("%d = ", n);

	for (int i = 2; i <= n; i++)
	{
    
    
		while (i != n) {
    
     
			if (n % i == 0)
			{
    
     //能整除说明i是n的因子之一
				printf("%d *", i);
				n = n / i; //找到一个因子i,n/i后缩短n继续找
			}else{
    
    
				break; //不能整除,跳出这次循环,递增i进行下一轮
			}
		}
	}
	printf("%d", n); //最后剩下的n不能整除i,也是因子之一
	return 0;
}

Insert image description here

5. Question: Use the nesting of conditional operators to complete this question: students with academic scores >= 90 points are represented by A, students with scores between 60-89 are represented by B, and students with scores below 60 are represented by C.

  • Analysis: Use if judgment or ternary operator
  • Code:
#include <stdio.h>
int main()
{
    
    
	int score;
	char grade;
	printf("请输入成绩:");
	scanf("%d", &score);

	grade = (score >= 90)? 'A' : ((score >= 60) ?'B' : 'C');

	printf("%c", grade); 
	return 0;
}

Insert image description here

6. Question: Input two positive integers m and n, find their greatest common divisor and least common multiple.

  • Analysis: Use the rolling method.
    • Greatest common divisor : Suppose there are two numbers a and b, find the remainder c=a % b when dividing the two numbers. If the remainder is 0, then b is the greatest common divisor . If b is not zero, a=b,b=c, continue the loop calculation.
    • Least common multiple : The least common multiple of two numbers is equal to the product of the two numbers divided by the greatest common divisor of the two numbers . That is: x, y's least common multiple min (common multiple) = x*y÷max (common divisor).
  • Code:
#include <stdio.h>
int main()
{
    
    
	int a = 0;
	int b = 0;
	printf("请输入两个正整数:");
	scanf("%d %d", &a, &b);
	int z = a * b;
	// 最大公约数
	int c = 0;
	while (a % b != 0){
    
    
		c = a % b;
		a = b;
		b = c;
	}
	printf("最大公约数:%d\n", b);
	
	// 最小公倍数
	int min = z / b;
	printf("最小公倍数:%d\n", min);
	return 0;
}

Insert image description here

7. Question: Enter a line of characters and count the number of English letters, spaces, numbers and other characters in it.

  • Analysis: Using the while statement, the condition is that the input character is not '\n'.
  • Code:
#include <stdio.h>

int main()
{
    
    
	// 定义英文字母的个数 english
	// 定义空格字符的个数 space
	// 定义数字字符的个数 digit
	// 定义其他字符的个数 other
	char c;
	int english = 0, space = 0, digit = 0, other = 0;
	printf("请输入一行字符:");
	//运用getchar逐个识别,回车结束
	while ((c = getchar()) != '\n') {
    
     
		if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
    
    
			english++;
		}else if (c == ' ') {
    
    
			space++;
		}else if (c >= '0' && c <= '9') {
    
    
			digit++;
		}else{
    
    
			other++;
		}
	}
	printf("英文字母个数:%d,空格字符个数:%d,数字字符个数:%d,其他字符个数:%d",english,space,digit,other);

	return 0;
}

Insert image description here

8. Question: Find the value of s=a+aa+aaa+aaaa+aa...a, where a is a number.

  • For example, 2+22+222+2222+22222 (a total of 5 numbers are added at this time), and the addition of several numbers is controlled by the keyboard.
  • Code:
#include <stdio.h>

int main()
{
    
    
	int a = 0,n = 0;
	int sum = 0,tempsum = 0,temp = 1;
	printf("请输入(0 - 9)一个整数:");
	scanf("%d", &a); //数字
	printf("请输入整数相加的个数:");
	scanf("%d", &n); //次数
	for (int i = 1; i <= n; i++)
	{
    
    
		tempsum += a * temp;
		sum += tempsum;
		temp *= 10;

	}
	printf("最后结果是:%d", sum);

	return 0;
}

Insert image description here

9. Question: If a number is exactly equal to the sum of its factors, the number is called a "perfect number".

  • For example, 6=1+2+3. Program to find all perfect numbers within 1000.
  • Factors : All numbers that can divide this number are called factors.
  • Perfect number : The sum of all factors of a natural number except itself is equal to the number , then the number is called a perfect number. So 1 is not a perfect number , so there is no need to consider 1.
  • Code:
#include <stdio.h>

int main()
{
    
    
	int s;
	printf("1000内的完数是:");
	for (int i = 2; i < 1000; i++) {
    
    
		s = 0;
		for (int j = 1; j < i; j++) {
    
     
			if ((i % j) == 0) {
    
     //求i与1到j的余数,若余数为0,则j为因子
				s += j;
			}
		}
		if (s == i) {
    
     // 因子相加与该数值相等,则为完数
			printf("%d \t", i);
		}
	}

	return 0;
}

Insert image description here

10. Question: A ball falls freely from a height of 100 meters. Each time it hits the ground, it bounces back to half of its original height. When it falls again, how many meters does it pass in total when it hits the ground for the 10th time? How high is the 10th rally?

  • Analysis: Note that the rebound height in the total number of meters passed when landing for the nth time must be *2, because rebound -> landing, the height of the two rebounds.
  • Code:
#include <stdio.h>

int main()
{
    
    
	float s = 100.0, h = s / 2;
	for (int n = 2; n <= 10; n++) {
    
    
		s = s + 2 * h; //第n次落地时共经过多少米
		h = h / 2; //第n次反跳高度
	}
	printf("第10次落地时共经过:%f米\n", s);
	printf("第10次反弹高度为:%f米\n", h);

	return 0;
}

Insert image description here

11. Question: There are numbers 1, 2, 3, and 4. How many different three-digit numbers can be formed without repeated numbers? How many are they?

  • Analysis: The numbers that can be filled in the hundreds, tens, and ones digits are 1, 2, 3, and 4. After composing all the permutations, remove the permutations that do not meet the conditions.
  • Code:
#include <stdio.h>

int main()
{
    
    
	int count = 0;
	for (int i = 1; i <= 4; i++) {
    
    
		for (int j = 1; j <= 4; j++) {
    
    
			for (int k = 1; k <= 4; k++) {
    
    
				if (i != j && i != k && j != k) {
    
    
					printf("%d%d%d\t", i, j, k);
					count++;
				}				
			}
		}
	}
	printf("\n组成%d个互不相同且不重复的三位数", count);

	return 0;
}

Insert image description here

12. Question: The bonuses issued by enterprises are based on profits.

  • When the profit is less than or equal to 100,000 yuan, the bonus can be increased by 10%;
  • When the profit is more than 100,000 yuan and less than 200,000 yuan, the commission is 10% for the part below 100,000 yuan, and 7.5% for the part above 100,000 yuan;
  • When the amount is between 200,000 and 400,000 yuan, the portion above 200,000 yuan can be commissioned 5%;
  • When the amount is between 400,000 and 600,000 yuan, the portion above 400,000 yuan can be commissioned at 3%;
  • When the amount is between 600,000 and 1 million, the portion above 600,000 yuan can be commissioned 1.5%;
  • When the amount exceeds 1 million yuan, a commission of 1% will be applied to the portion exceeding 1 million yuan. Enter the profit for the month from the keyboard. How should the total number of bonuses be distributed?
  • Analysis: Please use the number axis to divide and locate. Note that the bonus needs to be defined as an integer when defining.
  • Code:
#include <stdio.h>

int main()
{
    
    
	float money = 0,result = 0,temp = 0;
	printf("请输入当月利润:");
	scanf_s("%f", &money);
	if (money <= 10) {
    
    
		result = money * 0.1;
	}
	else if (money > 10 && money <= 20) {
    
    
		temp = money - 10;
		result = 10 * 0.1 + temp * 0.075;
	}
	else if (money > 20 && money <= 40) {
    
    
		temp = money - 20;
		result = 10 * 0.1 + temp * 0.05;
	}
	else if (money > 40 && money <= 60) {
    
    
		temp = money - 40;
		result = 10 * 0.1 + temp * 0.03;
	}
	else if (money > 60 && money <= 100) {
    
    
		temp = money - 60;
		result = 10 * 0.1 + temp * 0.015;
	}
	else
	{
    
    
		temp = money - 100;
		result = 10 * 0.1 + temp * 0.01;
	}
	printf("应发放奖金总数为:%f 万",result);

	return 0;
}

Insert image description here

13. Question: An integer, after adding 100, it becomes a perfect square number, and when added to 168, it becomes a perfect square number. What is the number?

  • Analysis: To judge within 100,000, first add 100 to the number before prescribing, then add 268 to the number and then prescribe. If the result after prescribing meets the following conditions, it is the result.
  • Code:
#include <stdio.h>
#include <math.h>

int main()
{
    
    
	int i,a,b;
	for ( i = 1; i < 100000; i++) {
    
    
		a = sqrt(i + 100); // a 是加上100之后开方后的结果
		b = sqrt(i + 268); // b 是加上268之后开方后的结果
		if (a* a == i + 100 && b * b == i + 268) {
    
    
			printf("%d\n", i);
		}
	}

	return 0;
}

Insert image description here

14. Question: Enter a certain year, a certain month and a certain day, and determine what day of the year this day is?

  • Analysis: Taking February 22, 2023 as an example, you should first add up the previous month, and then add 22 days, which is the day of the year. In special circumstances, if it is a leap year and the input month is greater than 3, you need to consider adding more one day.
  • Code:
#include <stdio.h>

int main()
{
    
    
	int day, month, year, sum;
	printf("请输入查询日期:\n");
	printf("请输入年份:");
	scanf_s("%d", &year);
	printf("请输入月份:");
	scanf_s("%d", &month);
	printf("请输入日期:");
	scanf_s("%d", &day);

	// 计算查询的月份之前月份的总天数,例如:查询3月,那么计算1-2月的总天数
	switch (month)
	{
    
    
		case 1:
			sum = 0;
			break;
		case 2:
			sum = 31;
			break;
		case 3: // 此时先按照是平年,即2月份是28天进行计算
			sum = 59;
			break;
		case 4:
			sum = 90;
			break;
		case 5:
			sum = 120;
			break;
		case 6:
			sum = 151;
			break;
		case 7:
			sum = 181;
			break;
		case 8:
			sum = 212;
			break;
		case 9:
			sum = 243;
			break;
		case 10:
			sum = 273;
			break;
		case 11:
			sum = 304;
			break;
		case 12:
			sum = 334;
			break;
		default:
			printf("输入错误,请重新输入!");
			break;
	}

	// 月份总天数再加上日期天数
	sum = sum + day;

	// 判断是否为闰年
	if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
    
    
		if (month > 2) {
    
     //如果是闰年且月份大于2,总天数加1
			sum++;
		}
	}

	printf("%d年%d月%d日的总天数为:%d", year, month, day, sum);

	return 0;
}

Insert image description here

15. Question: Input three integers x, y, z. Please output these three numbers from small to large.

  • Analysis: We find a way to put the smallest number on x , first compare x with y, if x>y then exchange the values ​​​​of x and y, and then compare x with z, if x>z then Swap the values ​​of x and z so that x is minimized.
  • Code:
#include <stdio.h>

int main()
{
    
    
	int x, y, z, tmp;
	printf("请输入三个整数:");
	scanf("%d%d%d", &x, &y, &z);
	// 将三个数中最小的放到x上,最大的放到z上
	if (x > y) {
    
     
		tmp = x;
		x = y;
		y = tmp;
	}
	if (x > z) {
    
    
		tmp = z;
		z = x;
		x = tmp;
	}
	// 上面交换后,最小的就在x上,此时只需要y和z比大小
	if (y > z) {
    
    
		tmp = y;
		y = z;
		z = tmp;
	}
	printf("从小到大:%d %d %d\n", x, y, z);

	return 0;
}

Insert image description here

16. Question: Use the * sign to output the pattern of the letter C.

  • Analysis: You can first write the letter C on the paper using the '*' sign, and then output it in separate lines.
  • Code:
#include <stdio.h>

int main()
{
    
    
	printf(" ****\n");
	printf(" *\n");
	printf(" * \n");
	printf(" ****\n");
	return 0;
}

Insert image description here

17. Question: Output special patterns.

  • Analysis: There are 256 characters in total. Different characters have different graphics.
  • Code:
#include <stdio.h>

int main()
{
    
    
	char a = 176, b = 219;
	printf("%c%c%c%c%c\n", b, a, a, a, b);
	printf("%c%c%c%c%c\n", a, b, a, b, a);
	printf("%c%c%c%c%c\n", a, a, b, a, a);
	printf("%c%c%c%c%c\n", a, b, a, b, a);
	printf("%c%c%c%c%c\n", b, a, a, a, b);

	return 0;
}

18. Question: Output the 9*9 formula.

  • Analysis: Consider rows and columns, there are 9 rows and 9 columns in total, i controls the rows and j controls the columns.
  • Code:
#include <stdio.h>

int main()
{
    
    
	int r;
	for (int i = 1; i <= 9; i++) {
    
    
		for (int j = 1; j <= 9; j++) {
    
    
			if (i >= j) {
    
    
				r = i * j;
				printf("%d * %d = %d\t", i, j, r);
			}		
		}
		printf("\n");
	}
	return 0;
}

Insert image description here

19. Question: It is required to output a chess board.

  • Analysis: Use i to control the rows, j to control the columns, and control the output of black squares or white squares according to the change of the sum of i+j.
  • A chess board is simply represented as an eight-by-eight matrix or grid, with a character displayed on the squares where the sum of the rows and columns is an even number, and the remaining positions are spaces.
  • Code:
#include <stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int i, j;
	for (i = 1; i <= 8; i++)
	{
    
    
		for (j = 1; j <= 8; j++) {
    
    
			if ((i + j) % 2 == 0) {
    
     // 行和列相加为偶数的是白格
				printf("■");
			}else {
    
    
				printf("  "); // 3个空格
			}				
		}		
		printf("\n");
	}

	return 0;
}

Insert image description here

20. Question: Print the stairs and print two smiling faces on the top of the stairs.

  • Analysis: Use i to control the rows, j to control the columns, and j to control the number of output black squares according to changes in i.
  • Code:
#include <stdio.h>

int main()
{
    
    
	printf("\1\1\n");//输出两个笑脸
	for (int i = 1; i < 11; i++){
    
    
		for (int j = 1; j <= i; j++) {
    
    
			printf("%c%c",219,219);
		}			
		printf("\n");
	}

	return 0;
}

Insert image description here

21. Topic: Monkey eating peach problem

  • The monkey picked a few peaches on the first day and ate half of them immediately. Not satisfied yet, he ate one more
  • The next morning I ate half of the remaining peaches and one more. From then on, every morning I ate half and one of the leftovers from the previous day.
  • When I wanted to eat more on the morning of the 10th day, I saw that there was only one peach left. Find out how many were picked on the first day.
  • Analysis: Adopt reverse thinking method and infer from back to front.
  • Code:
#include <stdio.h>

int main()
{
    
    
	// 从后往前推
	int day = 9,d1 = 0;
	int d2 = 1; //第10天只剩1个桃子
	while (day > 0) {
    
    
		d1 = (d2 + 1) * 2; //第1天的桃子数是 第2天的加1后 的2倍
		d2 = d1;
		day--;
	}
	printf("桃子总数为:%d", d1);

	return 0;
}

Insert image description here

22. Question: Two table tennis teams compete, each with three players.

  • Team A consists of three people a, b, and c, and team B consists of three people x, y, and z. Lots have been drawn to determine the match list. Someone asked the players about the roster for the game.
  • a said that he does not compete with x, and c said that he does not compete with x and z. Please program a program to find the list of players from the three teams.
  • Analysis: Compare sequentially in a loop, compare pairs, and use if to determine whether the participating players are repeated and the battle conditions.
  • Code:
#include <stdio.h>

int main()
{
    
    
	char a, b, c; // a、b、c三个选手
	for (a = 'x'; a <= 'z'; a++) {
    
    
		for (b = 'x'; b <= 'z'; b++) {
    
    
			if (a != b) {
    
     //避免重复比赛
				for (c = 'x'; c <= 'z'; c++) {
    
    
					if (c != a && c != b) {
    
     //避免重复比赛
						if (a != 'x' && c != 'x' && c != 'z') {
    
     //所给条件
							printf("a - %c\n b - %c\n c - %c\n", a, b, c);
						}
					}
				}
			}
		}
	}
	return 0;
}

Insert image description here

23. Question: Print out the following pattern (diamond)

Insert image description here

  • Analysis: First, divide the graph into two parts. The first four rows have one rule, and the last three rows have one rule. Use double for loops, the first layer controls the rows, and the second layer controls the columns.
  • The number of * in the pattern, from top to bottom: 1, 3, 5, 7, 5, 3, 1
  • The number of spaces in the pattern, from top to bottom: 3, 2, 1, 0, 1, 2, 3
  • Code:
#include <stdio.h>

int main()
{
    
    
	int i, j, k;
	//先打印前4行
	for (i = 1; i <= 4; i++) 
	{
    
    
		for (j = 1; j <= 4 - i; j++) {
    
     //每一行先打印需要打印的空格,空格数为(4 - 行号),譬如第1行,需要打4-1个空格,第2行需要打4-2个空格
			printf(" ");
		}
		for (k = 1; k <= 2 * i - 1; k++) {
    
     //打完空格打‘*',每行需要打印2倍行号-1个,譬如第1行打印2*1 - 1个,第2行打印2*2 - 1=3个
			printf("*");
		}
		printf("\n");
	}
	//然后打印后面三行,行号从1开始计算
	for (i = 1; i <= 3; i++) 
	{
    
    
		for (j = 1; j <= i; j++) {
    
     //每行打印空格数为行号数,譬如第1行打印1个,第2行打印2个
			printf(" ");
		}
		for (k = 1; k <= 7 - 2 * i; k++) {
    
     //每行打印7-2*i个’*',譬如第1行打印7-2*1=5个,第2行打印7-2*2=3个
			printf("*");
		}
		printf("\n");
	}
	
	return 0;
}

Insert image description here

24. Question: There is a sequence of fractions: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... Find the sum of the first 20 items of this sequence.

  • Analysis: Please grasp the changes in the numerator and denominator.
  • Code:
#include <stdio.h>

int main()
{
    
    
	float a = 2,b = 1,sum = 0,temp; // a为分子,b为分母
	for (int n = 1; n <= 20; n++) {
    
    
		sum = sum + a / b;	
		temp = a;
		// 后一项的分子 = 前一项的(分子+分母)
		a = a + b;
		// 后一项的分母 = 前一项的分子
		b = temp;
	}
	printf("数列的前20项之和为:%f", sum);

	return 0;
}

Insert image description here

25. Question: Find the sum of 1+2!+3!+…+20!

  • Analysis: This program just turns accumulation into cumulative multiplication.
  • Code:
#include <stdio.h>

int main()
{
    
    
	int a = 1,sum = 0; 
	for (int n = 1; n <= 20; n++) {
    
    
		a = a * n;
		sum = sum + a;	
	}
	printf("1+2!+3!+...+20!=%d", sum);

	return 0;
}

Insert image description here

26. Question: Use recursive method to find 5!.

  • Analysis:
    f(n) = n* (n - 1) * (n - 2) * …* 3* 2*1
    f(n) = n * f(n-1)
  • Code:
#include <stdio.h>

int f(int num) {
    
    
	if (num >= 1) {
    
    
		return num * f(num - 1);
	}else {
    
    
		return 1;
	}
}

int main()
{
    
    
	printf("5!=%d", f(5));
	return 0;
}

Insert image description here

27. Question: Use recursive function calling to print out the entered 5 characters in reverse order.

  • Analysis: In fact, if you output 5, it will keep calling recursively. When it reaches 1, it will output the last one first, and then return to the original function body to execute the next line, that is, output the second to last one, and then return to the original function body in sequence. , that is to say, you go in and come out.
  • Code:
#include <stdio.h>

void f(int n) {
    
    
	char c;
	if (n == 1) {
    
    
		c = getchar();
		putchar(c);
	}else {
    
    
		c = getchar();
		f(n - 1);
		putchar(c);
	}
}

int main() {
    
    
	void f(int n);
	printf("请输入5个字符:");
	f(5);
	return 0;
}

Insert image description here

28. Topic: There are 5 people sitting together

  • How old is the fifth person? He said he was 2 years older than the 4th person. When I asked the 4th person how old he was, he said he was 2 years older than the 3rd person.
  • I asked the third person and he said he was two years older than the second person. Asked the second person and said he was two years older than the first person. Finally I asked the first person and he said he was 10 years old. How old is the fifth person?
  • Analysis: Using the recursive method, recursion is divided into two stages: backtracking and recursion. If you want to know the age of the fifth person, you need to know the age of the fourth person, and so on, up to the first person (10 years old), and then back.
  • Code:
#include <stdio.h>

int age(int n) {
    
    
    int result;
    if (n == 1) {
    
    
        result = 10;
    }
    else {
    
    
        result = age(n - 1) + 2;
    }
    return result;
}

int main()
{
    
    
    printf("第5个人的年龄是:%d", age(5));
    return 0;
}

Insert image description here

29. Question: Given a positive integer with no more than 5 digits, the requirements are: 1. Find out how many digits it has, and 2. Print out the digits in reverse order.

  • Analysis: Decompose the input integer. If a five-digit number is input, then we will find the tens, thousands, hundreds, tens and units digits of the five-digit number. When outputting the final output, the units digit will be output first. , the reverse sequence is successfully implemented.
  • Code:
#include <stdio.h>

int main()
{
    
    
    int a, b, c, d, e, x;
    printf("请输入不多于5位数的正整数:");
    scanf("%d", &x);
    a = x / 10000;           //万位
    b = x % 10000 / 1000;   //千位
    c = x % 1000 / 100;     //百位
    d = x % 100 / 10;       //十位
    e = x % 10;             //个位
    if (a != 0) {
    
     //说明是5位数
        printf("输入的正整数是5位数\n");
        printf("逆序为:%d%d%d%d%d", e, d, c, b, a);
    }
    else if (b != 0) {
    
    
        printf("输入的正整数是4位数\n");
        printf("逆序为:%d%d%d%d", e, d, c, b);
    }
    else if (c != 0) {
    
    
        printf("输入的正整数是3位数\n");
        printf("逆序为:%d%d%d", e, d, c);
    }
    else if (d != 0) {
    
    
        printf("输入的正整数是2位数\n");
        printf("逆序为:%d%d", e, d);
    }
    else if (e != 0) {
    
    
        printf("输入的正整数是1位数\n");
        printf("逆序为:%d", e);
    }

    return 0;
}

Insert image description here

30. Question: A 5-digit number, determine whether it is a palindrome number. That is, 12321 is a palindrome number, the ones digit is the same as the thousands digit, and the tens digit is the same as the thousands digit.

  • Analysis: According to the definition of palindrome numbers, find out the tens of thousands, thousands, hundreds, tens, and ones digits, and then compare the ones digit with the tens of thousands digit, and compare the tens digit with the thousands digit.
  • Code:
#include <stdio.h>

int main() {
    
    

    int a, b, d, e, x;
    printf("请输入一个5位数:");
    scanf_s("%d", &x);
    a = x / 10000;           //万位
    b = x % 10000 / 1000;   //千位
    d = x % 100 / 10;       //十位
    e = x % 10;             //个位
    if (e == a && d == b) {
    
    
        printf("该数:%d是回文数!", x);
    }
    else {
    
    
        printf("该数:%d不是回文数!", x);
    }
	return 0;
}

Insert image description here

31. Question: Please enter the first letter of the day of the week to determine the day of the week. If the first letters are the same, continue to determine the second letter.

  • Analysis: It is better to use a situation statement. If the first letters are the same, use a situation statement or an if statement to judge the second letter.
  • monday tuesday wednesday thursday friday saturday sunday
  • Code:
#include <stdio.h>

int main() {
    
    

	char c;
	char j;
	printf("请输入星期的第一个字符:");
	c = getchar();
	getchar();//如果不加这个,导致下面第二次使用getchar时读入的是换行符并不是第二个输入的字符
	// monday tuesday wednesday thursday friday saturday sunday
	switch (c){
    
    
		case 'm':
			printf("monday\n");
			break;
		case 't':
			printf("请输入第2个字符:\n");
			j = getchar();
			if (j == 'u') {
    
    
				printf("tuesday\n");
			}
			if (j == 'h') {
    
    
				printf("thursday\n");
			}
			break;
		case 'w':
			printf("wednesday\n");
			break;
		case 'f':
			printf("friday\n");
			break;
		case 's':
			printf("friday\n");
			j = getchar();
			if (j == 'u') {
    
    
				printf("sunday\n");
			}
			if (j == 'a') {
    
    
				printf("saturday\n");
			}
			break;
		default:
			printf("输入有误,请重新再来!");
			break;
	}
    
	return 0;
}

Insert image description here

34. Topic: Practice function calls

  • Code:
#include <stdio.h>

void hello_world(void)
{
    
    
	printf("Hello, world!\n");
}
void three_hellos(void)
{
    
    
	int counter;
	for (counter = 1; counter <= 3; counter++) {
    
    
		hello_world();//调用此函数
	}		
}
int main()
{
    
    
	three_hellos();//调用此函数
	return 0;
}

Insert image description here

36. Question: Find prime numbers within 100

  • Analysis: A prime number refers to a prime number. Among the natural numbers greater than 1, there are no other natural numbers except 1 and itself.
  • Code:
#include <stdio.h>

int isPrime(int n) {
    
    
	if (n <= 1) {
    
    
		return 0;
	}
	for (int i = 2; i < n; i++) {
    
    
		if (n % i == 0) {
    
    
			return 0;
		}
	}
	return 1;
}

int main() {
    
    
	int isPrime(int n);
	for (int i = 2; i <= 100; i++) {
    
    
		if (isPrime(i)) {
    
    
			printf("%d\t", i);
		}
	}

	return 0;
}

Insert image description here

37. Topic: Sort 10 numbers

  • Analysis: You can use the selection method, that is, from the last 9 comparison processes, select the smallest one to exchange with the first element. By analogy next time, use the second element to compare with the last 8 elements and exchange them.
  • Code:
#include <stdio.h>

int main() {
    
    
	int a[10],temp;
	printf("请输入10个数字:\n");
	for (int i = 0; i < 10; i++) {
    
    
		scanf_s("%d", &a[i]);
	}
	for (int i = 0; i < 10; i++) {
    
    
		int min = i; //将第一个数作为最小的数
		for (int j = i + 1; j < 10; j++) {
    
    
			if (a[min] > a[j]) {
    
    
				min = j;
			}
		}
		temp = a[i];
		a[i] = a[min];
		a[min] = temp;
	}
	printf("排序后:\n");
	for (int i = 0; i < 10; i++) {
    
    
		printf("%d\t", a[i]);
	}

	return 0;
}

Insert image description here

38. Question: Find the sum of the diagonal elements of a 3*3 matrix

  • Analysis: a[i][i] is accumulated and output.
  • Code:
#include <stdio.h>

int main() {
    
    
	int a[3][3] = {
    
     1,3,4
				,5,7,9
				,4,7,1 };
	int sum = 0;
	for (int i = 0; i < 3; i++) {
    
    
		sum += a[i][i];
	}
	printf("对角线之和:%d", sum);
	return 0;
}

Insert image description here

39. Question: There is an array that has been sorted. Now enter a number and insert it into the array according to the original rules.

  • Analysis: First determine whether this number is greater than the last number, and then consider inserting the middle number. After insertion, the numbers after this element will be moved back one position in turn.
  • Code:
#include <stdio.h>

int main() {
    
    
	int a[11] = {
    
     1,4,6,9,13,16,19,28,40,100 };
	int length = sizeof(a) / sizeof(int);
	
	printf("原来的数组为:");
	for (int i = 0; i < length; i++) {
    
    
		printf("%-4d", a[i]);
	}
	printf("\n");

	// 插入一个数
	int b,i,j;
	printf("请输入插入的一个数:");
	scanf_s("%d", &b);
	if (b > a[9]) {
    
    
		a[10] = b;
	}else {
    
    
		// b插到什么位置
		// 先移动后插入
		for ( i = 0; i < length; i++) {
    
    
			if (a[i] < b) {
    
    
				continue; //跳出本次循环,进行下一次循环
			}else {
    
    
				for ( j = length - 1; j >= i; j--) {
    
    
					a[j + 1] = a[j]; //从后往前,把元素都后移一位,留出要插入的位置
				}
				a[j+1] = b; //插入
			}
			break;
		}
	}

	printf("之后的数组为:");
	for (int i = 0; i < length; i++) {
    
    
		printf("%-4d", a[i]);
	}
	printf("\n");
	return 0;
}

Insert image description here

40. Question: Output an array in reverse order.

  • Analysis: Swap the first and last.
  • Code:
#include <stdio.h>

int main() {
    
    
	int a[5] = {
    
     9,6,5,4,1 };
	int length = sizeof(a) / sizeof(int);
	
	printf("原来的数组为:");
	for (int i = 0; i < length; i++) {
    
    
		printf("%-4d", a[i]);
	}
	printf("\n");

	// 逆序
	int temp;
	for (int i = 0; i < length/2; i++) {
    
    
		temp = a[i];
		a[i] = a[length - 1 - i];
		a[length - 1 - i] = temp;
	}

	printf("之后的数组为:");
	for (int i = 0; i < length; i++) {
    
    
		printf("%-4d", a[i]);
	}
	
	return 0;
}

Insert image description here

41. Topic: Learn how to use static to define static variables

  • Analysis: The value of a static variable, when called, continues to change based on the current change each time. Usually used as a counter !
  • Before adding static modification:
#include <stdio.h>

void varfunc()
{
    
    
	int num = 5;
	num--;
	printf("当前num=%d\n", num);
}
void main()
{
    
    
	int i;
	for (i = 0; i < 3; i++) {
    
    
		varfunc();
	}
}

Insert image description here

  • After adding static modification:
#include <stdio.h>

void varfunc()
{
    
    
	static int num = 5; // static修饰
	num--;
	printf("当前num=%d\n", num);
}
void main()
{
    
    
	int i;
	for (i = 0; i < 3; i++) {
    
    
		varfunc();
	}
}

Insert image description here

42. Topic: Learn how to use auto to define variables locally

  • analyze:
    • The keyword auto is used to declare a variable as an automatic variable. Automatic variables are also called local variables.
    • Variables that are not defined in any class, structure, enumeration, union, and function are considered global variables, while variables defined within a function are considered local variables. All local variables are auto by default and are generally omitted.
    • A compilation error occurs when auto declares global variables. When auto declares local variables, the compilation is normal.
    • Auto modifies variables, and the variable type defaults to integer.
  • Code:
#include <stdio.h>

void main() {
    
    
	int i, num;
	num = 2;
	for (i = 0; i < 3; i++)
	{
    
    
		printf(" The num equal %d \n", num);
		num++;
		{
    
    
			auto  num = 1;
			printf(" The internal block num equal %d \n", num);
			num++;
		}
	}
}

Insert image description here

43. Topic: Learn how to use extern.

  • Analysis: If we need to reference a variable defined in another source file in one source file, we only need to declare the variable with the extern keyword in the referenced file.
  • Code:

A source file mytest.c

#include <stdio.h>
int number = 100000;

Another source file test.c

#include <stdio.h>
extern int number; //把number放到了一个外部文件进行初始化,通过关键字extern来声明调用这个number

void sell(){
    
    
	number--;
}
void main() {
    
    
	sell();
	printf(" number = %d \n", number);
}

Insert image description here

44. Topic: Scope of variables.

  • [1]: Global variables
#include <stdio.h>

int a = 1;
int b = 10;
int c;

void add() {
    
    
	c = a + b;
	printf("a = %d\n", a);
}

void main()
{
    
    
	add();
	printf("c = %d\n", c);
}

Insert image description here

  • [2]: Proximity principle
#include <stdio.h>

int a = 1;
int b = 10;
int c;

void add() {
    
    
	c = a + b;
	printf("a = %d\n", a);
}

void main()
{
    
    
	a = 20; 
	add(); // 会选择离的近的上面赋值的 a = 20
	printf("c = %d\n", c);
}

Insert image description here

  • [3]: Local variables
#include <stdio.h>

int a = 1;
int b = 10;
int c;

void add() {
    
    
	c = a + b;
	printf("a = %d\n", a);
}

void main()
{
    
    
	int a = 20;
	add(); //它只能调用上面全局变量的a,不能调用上面局部变量【a = 20】
	printf("c = %d\n", c);
}

Insert image description here

46. ​​Topic: define macro definition - define a variable

  • Analysis: Special variables are defined.
  • Code:
#include <stdio.h>
#define PI 3.1415926

int main()
{
    
    
	float r = 2;
	float s = PI * r * r;
	printf("%f\n", s);
}

Insert image description here

47. Topic: define macro definition - identifier

  • [1] Analysis: Define CH as a multiplication sign
  • Code:
#include <stdio.h>
#define PI 3.1415926
#define CH *
int main()
{
    
    
	float r = 2;
	float s = PI CH r CH r;
	printf("%f\n", s);
}

Insert image description here

  • [2] Analysis: Define the formula so that both int and float types can be used
  • Code:
#include <stdio.h>
#define PI 3
#define CH *
#define s(a,b) a*b*b
int main()
{
    
    
	float r = 2;
	int t = 3;
	printf("s(a,b) = %d\n", s(PI, t));
	printf("s(a,b) = %f\n", s(PI, r));
}

Insert image description here

48. Topic: Comprehensive application of #if #ifdef and #ifndef.

  • Analysis: The compiler did not compile this statement, and this statement did not generate assembly code.
  • 【1】#if is similar to if-else
  • Code:
#include <stdio.h>
#define MAX
#define MAXIMUM(x,y) (x>y)?x:y
#define MINIMUM(x,y) (x>y)?y:x
int main()
{
    
    
	#define A 0
	#if (A > 1)
		printf("A > 1");
	#elif (A == 1)
		printf("A == 1");
	#else 
		printf("A < 1");
	#endif

	return 0;
}

Insert image description here

  • [2] #ifdef
  • Analysis: #ifdef MAX means that if the MAX macro definition has been defined [that is, look forward to see if the macro definition of MAX], then execute the following statement
  • Code:
#include <stdio.h>
#define MAX
#define MAXIMUM(x,y) (x>y)?x:y
#define MINIMUM(x,y) (x>y)?y:x
int main()
{
    
    
	int a = 10, b = 20;
	#ifdef MAX
		printf("更大的数字是 %d \n", MAXIMUM(a, b));
	#else 
		printf("更小的数字是 %d \n", MINIMUM(a, b));
	#endif

	return 0;
}

Insert image description here

  • 【3】#ifndef
  • Analysis: #ifndef MAX means that if the MAX macro definition is not defined, the following statement will be executed.
  • Code:
#define MAX
#define MAXIMUM(x,y) (x>y)?x:y
#define MINIMUM(x,y) (x>y)?y:x
int main()
{
    
    
	int a = 10, b = 20;
	#ifndef MIN
		printf("更大的数字是 %d \n", MAXIMUM(a, b));
	#else 
		printf("更小的数字是 %d \n", MINIMUM(a, b));
	#endif

	return 0;
}

Insert image description here

50. Topic: Application exercises of #include

  • Analysis: Reference to another c function
  • Code:
  • test.c
#define PI 3.1415926
  • main.c
#include <stdio.h>
#include "test.c"
int main(){
    
    
	float r = 1.5;
	float area = PI * r * r;
	printf("area = %f\n",area);
	return 0;
}

Insert image description here

Guess you like

Origin blog.csdn.net/isak233/article/details/128767745