[Zhengzhou University C language experiment report answer 2023]

Article directory



Note: Errors will be reported when using vc6.0 and below:
Declare variables inside the for loop: for(int i=0;...)just declare them outside the loop instead.

Steps on the machine: (to be written in the first two experiments)
1.在D/E盘新建文件夹,最好命名为英文/数字
2.打开Visual C++ 6.0,点击左上角'文件',点击'新建'(或按ctrl+N)
insert image description here
点击最左边'文件',选择c++ source file,位置选择刚刚新建的文件夹,文件名命名为题号,点击确定,开始输入代码。
insert figure description here


1. Experiment 1: C language program structure and the whole process of program operation

1. Program and run on the computer, find the sum of three integers

#include <stdio.h>
int main() {
    
    
	int a, b, c;
	scanf("%d%d%d", &a, &b, &c);	// 输入三个整数
	printf("%d", a + b + c);	// 输出三个整数的和
	return 0;
}

2. Find the sum, difference, product and quotient of two numbers

#include <stdio.h>
int main() {
    
    
	float a, b;
	scanf("%f%f", &a, &b);	// 输入两个浮点数
	printf("%.2f\t%.2f\t%.2f\t%.2f\n", a + b, a - b, a * b, a / b); // 输出和差积商
	return 0;
}

3. Enter 5 numbers and find the sum of the squares of these 5 numbers

#include <stdio.h>
int main() {
    
    
	float a, b, c, d, e;
	scanf("%f%f%f%f%f", &a, &b, &c, &d, &e);	// 输入5个数
	printf("%f\n", a * a + b * b + c * c + d * d + e * e);	// 输出平方和
	return 0;
}

4. Find the sum of the square roots of three numbers

#include <stdio.h>
#include <math.h>
int main() {
    
    
	double a, b, c;
	scanf("%lf%lf%lf", &a, &b, &c);	//输入三个数
	printf("%f", sqrt(a) + sqrt(b) + sqrt(c));	// 输出平方根和
	return 0;
}

5. Enter the radius of the circle to find the area and circumference of the circle

#include <stdio.h>
#define pi 3.14159	// 宏定义π的值
int main() {
    
    
	double r;
	scanf("%lf", &r);	// 输入圆的半径
	printf("s=%f\n", pi * r * r);	// 圆的面积
	printf("c=%f\n", pi * 2 * r);	// 圆的周长
	return 0;
}

6. Output on screen

#include <stdio.h>
int main() {
    
    
	printf("What a beautiful campus!\n");	// 这不需要注释了吧
	printf("I wish you every success!\n");	// 是的
	return 0;
}

2. Experiment 2: Data types and C language expressions

1. Find the value of the polynomial ax³+bx²+c (a=2, b=3, c=4, x=1.414)

这里用pow函数计算幂值,pow(a,b)表示a的b次方,需要引入头文件math.h

#include <stdio.h>
#include <math.h>
int main() {
    
    
	int a = 2, b = 3, c = 4;
	double x = 1.414, s;
	s = a * pow(x, 3) + b * pow(x, 2) + c;	
	// pow(a,b)表示a的b次方
	printf("%f", s);
	return 0;
}

2. Input two numbers a and b, and find their product, quotient and remainder respectively

The code is as follows (example):

#include <stdio.h>
int main() {
    
    
	int a, b, p, r;
	float q;
	scanf("%d%d", &a, &b);
	p = a * b;	// p为积
	q = (float)a / b;	// q为商,因为a,b为整形变量,所以将a强制转换成浮点数,可得结果为浮点数的商
	r = a % b;	// r为余数
	printf("积:%d\n商:%f\n余数:%d\n", p, q, r);
	return 0;
}

C=5/9(F-32)3. Given the Fahrenheit temperature F, calculate the Celsius temperature C according to the formula (retain two decimal places for the result)

#include <stdio.h>
int main() {
    
    
	double F, C;
	scanf("%lf", &F);	// 输入华氏度
	C = 5.0 / 9 * (F - 32);	// 用公式转为摄氏度,整型变量相除结果仍未整数,故变为浮点数运算
	printf("C = %0.2f", C);	// 输出摄氏度保留两位小数
	return 0;
}

4. Use the macro definition to define the symbolic constant PI, whose value is 3.14159, and use the symbolic constant to find the circumference and area of ​​the circle when the radius of the circle is r=2.456

#include <stdio.h>
#define PI 3.14159	// 宏定义符号常量PI
int main() {
    
    
	double r = 2.456, c, s;
	c = 2 * PI * r;	// 圆的周长
	s = PI * r * r;	// 圆的面积
	printf("C = %f\nS = %f\n", c, s);
	return 0;
}

5. If float c = 3.123456789the value of c is output according to the real type f, observe the change of the value after rounding

#include <stdio.h>
int main() {
    
    
	float c = 3.123456789;
	printf("%f\n", c);
	return 0;
}

The output result is 3.123457, because the float type usually occupies 4 bytes, and a number and a punctuation each occupy a byte

6. Find the value of a after compound assignment in the following format

int a = 2; a+=a; a-=2; a*=2+3; a/=a+a;

#include <stdio.h>
int main() {
    
    
	int a = 2;
	a += a; // a = a + a = 4
	a -= 2; // a = a - 2 = 2
	a *= 2 + 3; // a = a * (2 + 3) = 10
	a /= a + a; // a = a / (a + a) = 10/20 = 0.5 ∵a为整形,∴结果为 0 
	printf("%d", a);
	return 0;
}

3. Experiment 3: Input and output functions and format characters

1. If a=3,b=4,c=5,x=1.414,y=1.732,z=2.712you write a program, it is required to output in the following format:

a=3⁡ ⁡⁡ ⁡ ⁡⁡ ⁡ ⁡ ⁡⁡⁡ ⁡ ⁡b=4⁡ ⁡⁡ ⁡ ⁡⁡ ⁡ ⁡ ⁡⁡ ⁡⁡ c=5
x=1.414 y=1.732 z=2.712

#include <stdio.h>
int main() {
    
    
	int a = 3, b = 4, c = 5;
	float x = 1.414, y = 1.732, z = 2.712;
	printf("a=%-7db=%-7dc=%-7d\nx=%-7.3fy=%-7.3fz=%-7.3f\n", a, b, c, x, y, z);
	return 0;
}

'-' is left-aligned, unsigned is right-aligned, the number is the field width of the data, if it is insufficient, fill it with spaces

2. If a=3,b=4,c=5,x=1.414,y=1.732,z=2.712, write a program, it is required to use 6 scanf() functions to complete the output:

a=3⁡ ⁡⁡ ⁡ ⁡⁡ ⁡ ⁡ ⁡⁡⁡ ⁡ ⁡b=4⁡ ⁡⁡ ⁡ ⁡⁡ ⁡ ⁡ ⁡⁡ ⁡⁡ c=5
x=1.414 y=1.732 z=2.712

#include <stdio.h>
int main() {
    
    
	int a, b, c;
	float x, y, z;
	scanf("%d", &a);scanf("%d", &b);scanf("%d", &c);
	scanf("%f", &x);scanf("%f", &y);scanf("%f", &z);
	printf("a=%-7db=%-7dc=%-7d\nx=%-7.3fy=%-7.3fz=%-7.3f\n", a, b, c, x, y, z);
	return 0;
}

3. If a=3,b=4,c=5,x=1.414,y=1.732,z=2.712, when writing a program, it is required to use a scanf() function to complete the input, and output in the following format

x1=a+b+c= 3+ 4+ 5= 12
x2=a-b-c= 3- 4- 5= -6

#include <stdio.h>
int main() {
    
    
	int a, b, c;
	scanf("%d%d%d", &a, &b, &c);
	printf("x1=a+b+c=%2d+%2d+%2d=%3d\n"
	       "x2=a-b-c=%2d-%2d-%2d=%3d\n", a, b, c, a + b + c, a, b, c, a - b - c);
	return 0;
}

3,4,5 are right-aligned, width 2, the result is right-aligned width 3

4. Assign 'A', 'B', 'C', and 'D' to c1, c2, c3, and c4 respectively, and use a scanf() function to complete the input, and then display the ASCII codes corresponding to these four characters

#include <stdio.h>
int main() {
    
    
	char c1, c2, c3, c4;
	scanf("%c%c%c%c", &c1, &c2, &c3, &c4);
	printf("A=%d\tB=%d\tC=%d\tD=%d\n", c1, c2, c3, c4); // 字符输出为整形格式显示为ASCII码
	return 0;
}

5. Assign 60, 61, 62, and 63 to d1, d2, d3, and d4 respectively, and use d1, d2, d3, and d4 to display the corresponding ASCII code characters 'A', 'B', 'C', and 'D'

#include <stdio.h>
int main() {
    
    
	int d1 = 60, d2 = 61, d3 = 62, d4 = 63;
	d1 += 5;d2 += 5;d3 += 5;d4 += 5;
	// ABCD的ASCII码分别是65.66.67.68
	printf("%c%c%c%c\n", d1, d2, d3, d4);
	return 0;
}

6. Assign 12345678 and 3456789 to m and n respectively, and then output the values ​​correctly

#include <stdio.h>
int main() {
    
    
	int m = 12345678, n = 3456789;
	printf("m = %d\nn = %d\n", m, n);	// m不对,n是对的,因为的顺子不能带A和2
	return 0;
}

7. Convert 20, 64, 127 into octal and hexadecimal numbers and output

#include <stdio.h>
int main() {
    
    
	int a = 20, b = 64, c = 127;
	printf("20的八进制为:%o,十六进制为:%X\n"		// %o 表示输出八进制整数
	       "64的八进制为:%o,十六进制为:%X\n"		// %X 表示输出带有大写字母的十六进制整数
	       "127的八进制为:%o,十六进制为:%X\n", a, a, b, b, c, c);
	return 0;
}

8. If a=3,b=4,c=5,x=1.414,y=1.732,z=2.712you write a program, it is required that the number field width of each data is 6 digits and the decimal place is 2 digits when outputting.

#include <stdio.h>
int main() {
    
    
	float x = 1.414, y = 1.732, z = 2.712;
	printf("%6.2f%6.2f%6.2f\n", x, y, z);	// %m.nf m表示数据域宽,n表示保留小数位数
	return 0;
}

9. Calculate and output 1/3 of the decimal value, keep 6 decimal places with % (0.333333%)

#include <stdio.h>
int main() {
    
    
	double a = 1;
	printf("%.6f%%", a / 3);
	// 两个%%输出成一个%。
	// ∵%通常用作格式化,如果直接输出%,编译器无法确定其含义
	return 0;
}

10. Use getchar() to input 'A', 'B', 'C' respectively, and assign them to a, b, c, then convert them into corresponding lowercase letters, and use putchar() to output them

#include <stdio.h>
int main() {
    
    
	char a, b, c;
	a = getchar();b = getchar();c = getchar();
	a += 32;b += 32;c += 32;
	// 小写字母比对应大写字母ASCII码值大32
	putchar(a);putchar(b);putchar(c);
	return 0;
}

4. Experiment 4: Select structure program design

1. Input three integers a, b, c from the keyboard, and output the largest number among them

#include <stdio.h>
int main() {
    
    
	int a, b, c;
	scanf("%d%d%d", &a, &b, &c);	// 输入a,b,c
	if (b > a) a = b;	// a和b比较,b大就把b值赋给a
	if (c > a) a = c;	// a和c比较,c大就把c值赋给a
	printf("%d", a);
	return 0;
}

2. There is a function, write a program, input an integer x, and output the value of y

#include <stdio.h>
int main() {
    
    
	int x;
	scanf("%d", &x);
	if (x < 1)
		printf("%d\n", x);
	else if (x < 10)
		printf("%d\n", 2 * x - 1);
	else
		printf("%d\n", 3 * x - 11);
	return 0;
}

The premise of the else if judgment is that the if judgment is no, so at this time x>=1, only need to judge x<10.

3. Give a hundred-point grade, and ask to output the corresponding grades of 'A', 'B', 'C', 'D', 'E', and 'A' for more than 90 points...

There are too many words so I don’t need to type them, I understand everything

#include <stdio.h>
int main() {
    
    
	int score;
	scanf("%d", &score);
	switch (score / 10) {
    
    	// 分数除以10,取十位数
		case 10:	// 100
		case 9:		// 90-99
			printf("A");
			break;
		case 8:		// 80-89
			printf("B");
			break;
		case 7:		// 70-79
			printf("C");
			break;
		case 6:		// 60-69
			printf("D");
			break;
		default:	// 0-59
			printf("E");
	}
	return 0;
}

4. Randomly input an integer of no more than five digits from the keyboard to complete the following tasks:

①Find how many digits it is
②Output each number separately
③Output the digits in reverse order

①求它是几位数

void num(int n) {
    
    
	int sum = 0;
	while (n) {
    
    		// 循环直至n=0
		n /= 10;	// n/10相当于去掉n的个位数
		sum++;		// 每去掉一位,计数+1
	}
	printf("它是%d位数\n", sum);
}

②分别输出每一个数字

void digit(int n) {
    
    	// 分别输出每一位数字
	int a[5];	// 存放每一位数,不超过5位
	int i = 0;
	while (n) {
    
    	// n=0时退出循环
		a[i++] = n % 10;	// 取出n的个位数
		n /= 10;	// 去掉n的个位数
	}
	while (--i >= 0)	// ∵个位数在数组首位,∴逆序输出数组
		printf("%d\n", a[i]);
}

③按逆序输出各位数字

void reverse(int n) {
    
    	//逆序输出数字
	int re = 0;		// 存储逆序后的数字
	while (n) {
    
    
		int d = n % 10;	// 取出n的个位数
		re = re * 10 + d;	// 依次加到re的末尾
		n /= 10;	// 去掉n的个位数
	}
	printf("%d\n", re);
}

主函数

int main() {
    
    
	void num(int);
	void digit(int);
	void reverse(int);
	int n;
	scanf("%d", &n);
	num(n);		// 逐个运行函数
	digit(n);
	reverse(n);
	return 0;
}

5. To find the root of the equation ax²+bx+c=0, where a, b, and c are entered by the keyboard, there are the following situations:

①a=0, not a quadratic equation;
②b²-4ac=0, there are two equal real roots;
③b²-4ac>0, there are two unequal real roots;
④b²-4ac<0, there are two conjugate complex roots.

#include <stdio.h>
#include <math.h>
int main() {
    
    
	double a, b, c, x1, x2, D;
	scanf("%lf%lf%lf", &a, &b, &c);	// 输入a,b,c
	D = b * b - 4 * a * c;		// D表示△
	if (a == 0) {
    
    				// a=0时求解一次方程
		x1 = -1.0 * c / b;
		printf("a=0,不是二次方程,x=%f\n", x1);
	}
	if (a != 0) {
    
    
		if (D > 0) {
    
    			// △> 0, 利用求根公式求方程的解
			x1 = (-1.0 * b + sqrt(D)) / 2 * a;
			x2 = (-1.0 * b - sqrt(D)) / 2 * a;
			printf("有两个不等实根,x1=%.2f\nx2=%.2f\n", x1, x2);
		} else if (D == 0) {
    
    
			x1 = -1.0 * b / 2 * a;
			printf("有两个相等实根,x1=x2=%.2f\n", x1);
		} else {
    
    				// △< 0,有两个共轭复根,求出实部与虚部,x1表示实部,x2表示虚部
			x1 = -1.0 * b / 2 * a;
			x2 = sqrt(-1.0 * D) / 2 * a;
			printf("有两个共轭复根,x1=%.2f + %.2fi\nx2=%.2f - %.2fi", x1, x2, x1, x2);
		}
		return 0;
	}
}

5. Experiment 5: Cycle (1)

1. Calculate and output the result

s = ∑ n = 1 100 n s=\sum_{n=1}^{100} n s=n=1100n

#include <stdio.h>
int main() {
    
    
	int s = 0;
	for (int i = 1; i <= 100; i++)	// 遍历1到100整数,累加到s中
		s += i;
	printf("%d\n", s);
	return 0;
}

2. Calculate and output the result

s u m = ∑ n = 1 10 n ! sum=\sum_{n=1}^{10} n! sum=n=110n!

#include <stdio.h>
int main() {
    
    
	int sum = 0;
	for (int i = 1; i <= 10; i++) {
    
    	// 外层遍历1到10的整数
		int n = 1;	// n存储阶乘的值,初始化为1
		for (int j = 1; j <= i; j++) // 内层循环计算i的阶乘
			n *= j;	// 将1到i依次乘入n中
		sum += n;	// 将当前阶乘累加到s中
	}
	printf("%d\n", sum);
	return 0;
}

3. Calculate the sum of the following formulas, requiring the last item to be less than 1 0 − 5 10^{-5}105

1 − 1 5 + 1 10 − 1 17 + ⋯ 1-\frac{1}{5}+\frac{1}{10}-\frac{1}{17}+\cdots 151+101171+       Hint: The general formula is( − 1 ) n − 1 1 n 2 + 1 (-1)^{n-1}\frac{1}{n^{2}+1}(1)n1n2+11

#include <stdio.h>
#include <math.h>
int main() {
    
    
	double s = 1, n = 2, a = 1;	// s为级数的和,n为项数,a为每一项的值
	while (a >= 1e-5) {
    
    		// 最后一项小于1e-5时退出循环
		a = pow(-1.0, n - 1) / (n * n + 1);	// 公式计算
		n++;
		s += a;
	}
	printf("%f\n", s);
	return 0;
}

4. Enter 30 characters and count the numbers, letters and characters among them.

#include <stdio.h>
int main() {
    
    
	int C, n = 0, a = 0, c = 0, count = 0;
	// C存储字符ASCII码,n,a,c统计数字字母字符数量,count计算输入字符总数量
	while ((C = getchar()) != '\n') {
    
    	// 循环读取输入字符直到遇见回车
		if (C >= '0' && C <= '9') n++;	// 数字+1
		else if ((C >= 'A' && C <= 'Z') || (C >= 'a' && C <= 'z')) a++;	// 字母+1
		else c++;	// 字符+1
		count++;	// 总数+1
		if (count >= 30)	// 超出30个不统计
			break;
	}
	printf("数字%d\t字母%d\t字符%d\n", n, a, c);
	return 0;
}

5. Find the first 20 items of Feibo Naqi sequence

1,1,2,3,5,8,13,21…

#include <stdio.h>
int main() {
    
    
	int x1 = 1, x2 = 1, x3;	// 前两项为1,1
	printf("1\n1\n");
	for (int i = 3; i <= 20; i++) {
    
       // 从第三项开始循环计算
		x3 = x1 + x2;              // 计算当前项
		printf("%d\n", x3);       // 输出当前项
		x1 = x2;                  // 更新前两项
		x2 = x3;
	}
	return 0;
}

6. Experiment 6: Cycle (2)

1. Use the double loop structure to calculate and output the result.

s = ∑ n = 1 10 n ! s=\sum_{n=1}^{10} n! s=n=110n!

#include <stdio.h>
int main() {
    
    
	int sum = 0;	// 定义一个变量 sum,用于累加每个数的阶乘
	for (int i = 1; i <= 10; i++) {
    
    
		int n = 1;		// 定义变量 n,用于计算 i 的阶乘,初始值为 1
		for (int j = 1; j <= i; j++) 
			n *= j;		// 将当前数乘上前面所有的数,得到 i 的阶乘
		sum += n;		// 将 i 的阶乘累加到 sum 变量中
	}
	printf("%d\n", sum);
	return 0;
}

2. Loop output ninety-nine multiplication table

#include <stdio.h>
int main() {
    
    
	for (int i = 1; i <= 9; i++) {
    
    
		for (int j = 1; j <= i; j++)
			printf("%d×%d=%d\t", j, i, j * i);
		printf("\n");
	}
	return 0;
}

3. Output the following graphics respectively

(1)  1   
    121
  12321
   1234321
(1)

#include <stdio.h>
int main() {
    
    
	int k;
	for (int i = 1; i <= 4; i++) {
    
    	// 共输出4行
		for (int j = 4 - i; j > 0; j--)
			printf(" ");	// 每行前的空格
		for (k = 1; k <= i; k++)
			printf("%d", k);	// 左半边数字 1234
		for (k = k - 2; k > 0; k--) 
			printf("%d", k);	// 右半边数字 321
		printf("\n");
	}return 0;
}

(2) A  
   BBB  
   CCCCC  
 DDDDDDD 

#include <stdio.h>
int main() {
    
    
	char c = 65;	// 值为'A'的ASCII码
	for (int i = 1; i <= 4; i++) {
    
    	// 共4行
		for (int j = 4 - i; j > 0; j--)	
			printf(" ");	// 打印每行前的空格,逐行递减
		for (int k = 1; k < 2 * i; k++)
			printf("%c", c);// 打印字母,逐行递增
		printf("\n");
		c++;	// 字母变量递增,由'A'变为'B'再变'C''D'
	}
	return 0;
}

(3)  *
    * + *
   * + * + *
   * + * + * + *

#include <stdio.h>
int main() {
    
    
	for (int i = 1; i <= 4; i++) {
    
    	// 共4行
		for (int j = 4 - i; j > 0; j--)
			printf(" ");	// 第一行3个空格,每行前面的空格少1
		for (int k = 1; k <= 2 * i - 1; k++) // 每行字符数量为2*i-1
			if (k % 2 == 0)
				printf("+");	// 偶数位 +
			else
				printf("*");	// 奇数位 *
		printf("\n");
	}
	return 0;
}

4. Balabala, an ancient mathematician, bought a hundred chickens for a hundred dollars, and the rooster was 1! 5! , one mother hen three, one chick three one

#include <stdio.h>
int main() {
    
    
	for (int x = 0; x <= 20; x++)	// 公只因5块一只,100最多买20只
		for (int y = 0; y <= 33; y++) {
    
    	//母只因3块一只,100最多买33只
			int z = 100 - x - y;	// 总共能买100只,剩下就都是小只因
			if (5 * x + 3 * y + z / 3 == 100)
				printf("鸡翁%d,鸡母%d,鸡雏%d\n", x, y, z);
		}
	return 0;
}

5.求 s = 1 + ( 1 + 2 ) + ( 1 + 2 + 3 ) + ⋯ s=1+(1+2)+(1+2+3)+\cdots s=1+(1+2)+(1+2+3)+ , and output the result

#include <stdio.h>
int main() {
    
    
	int s = 0, n;
	scanf("%d", &n);	// 共n项
	for (int i = 1; i <= n; i++) {
    
    
		int a = 0;
		for (int j = 1; j <= i; j++)
			a += j;		// a为每一项的值
		s += a;			// s为前n项和
	}
	printf("%d\n", s);
	return 0;
}

6. Given that x, y, and z are numbers from 0 to 9, find the values ​​of x, y, and z so that the formula holds: xxz+yzz=532.

// xxz+yzz =532
#include <stdio.h>
int main() {
    
    
	int x, y, z;
	for (x = 1; x <= 9; x++)	// x作为首位不能为0
		for (y = 0; y <= 9; y++)
			for (z = 0; z <= 9; z++)
				if (110 * x + 100 * y + 12 * z == 532)
				// x作了百位和十位,y作了一次百位,z作了一次十位两次个位
					printf("x=%-3dy=%-3dz=%-3d\n", x, y, z);
	return 0;
}

7. A company’s annual sales revenue increases by 10% compared with the previous year. According to this growth rate, how many years will it take to achieve the goal of quadrupling sales revenue?

翻两番为原来的4倍(有人一开始不知道,是谁我不说)

#include <stdio.h>
int main() {
    
    
	double x = 1;	// 初始收入为100%
	int year = 0;
	while (x < 4) {
    
    	// 当收入达到400%时停止循环
		x *= 1.1;	// 每年增长10%
		year++;
	}
	printf("%d\n", year);
	return 0;
}

8. Find the largest three prime numbers between 100 and 999

#include <stdio.h>
#include <math.h>
int main() {
    
    
	int j, a[3];	// a[3]存储最大的3个元素
	for (int i = 101; i <= 999; i += 2) {
    
    
		int k = sqrt(i);
		for (j = 2; j <= k; j++)
			if (i % j == 0)
				break;
		if (j > k) {
    
    	// 判断素数
			for (int i = 1; i < 3; i++)
				a[i - 1] = a[i];	// 将原先三个元素向前移动,最后一位被空出来
			a[2] = i;	// 新的最大的素数放入最后一位,第一位最小的元素被挤出去
		}				// 不断更新最大的素数
	}
	for (int i = 0; i < 3; i++)
		printf("%d\n", a[i]);	// 打印出最大的三个素数的数组
	return 0;
}

7. Experiment 7: Array (1)

1. Randomly generate 10 positive integers of [50,100], find the maximum value, minimum value and average value, and display the value of the entire array and the obtained result

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int a[10], t, s = 0;
	for (int i = 0; i <= 9; i++) {
    
     // 随机生成50-100的10个数
		a[i] = 50 + rand() % 51;
		s += a[i]; // 求和,后续求平均值
		printf("%d\n", a[i]);	// 显示数组的值
	}
	for (int i = 0; i <= 8; i++) // 冒泡法排序
		for (int j = 0; j <= 8 - i; j++)
			if (a[j] > a[j + 1]) {
    
    
				t = a[j];
				a[j] = a[j + 1];
				a[j + 1] = t;
			}
	printf("最小值%d\n最大值%d\n平均值%d\n", a[0], a[9], s / 10);
	return 0;
}

2. Randomly generate the grades of 20 students for one course and display them; count the number of people in each grade and display the results

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int a[20], A = 0, B = 0, C = 0, D = 0, E = 0;
	for (int i = 0; i <= 19; i++) {
    
     // 生成0-100随机数组
		a[i] = rand() % 101;
		printf("%d\n", a[i]);
		switch (a[i] / 10) {
    
    		// 每个成绩对应的等级
			case 10:	// 100
			case 9:		// 90-99
				A++;	
				break;
			case 8:		// 80-89
				B++;
				break;
			case 7:		// 70-79
				C++;
				break;
			case 6:		// 60-69
				D++;
				break;
			default:	// 剩下的,即0-59
				E++;
		}
	}
	printf("0~59:%d人\n", E);
	printf("60~69:%d人\n", D);
	printf("70~79:%d人\n", C);
	printf("80~89:%d人\n", B);
	printf("90~100:%d人\n", A);
	return 0;
}

3. Randomly generate 10 positive integers within 50, sort from small to large, and display the results before and after sorting

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int a[10], t;
	printf("排序前:\n");
	for (int i = 0; i < 10; i++) {
    
    	// 随机生成10个成绩
		a[i] = rand() % 50;
		printf("%d\n", a[i]);		// 显示排序前成绩
	}
	for (int i = 0; i <= 8; i++)  // 冒泡法排序
		for (int j = 0; j <= 8 - i; j++)
			if (a[j] < a[j + 1]) {
    
    
				t = a[j];
				a[j] = a[j + 1];
				a[j + 1] = t;
			}
	printf("排序后:\n");
	for (int i = 0; i < 10; i++)
		printf("%d\n", a[i]);	// 显示排序后成绩
	return 0;
}

4. Randomly generate 20 positive integers within 100 and store them in a one-bit array, and then output them in four lines, with five numbers in each line

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int a[20];
	for (int i = 1; i <= 20; i++) {
    
    	// 随机生成20个数
		a[i-1] = rand() % 100;
		printf("%d\t", a[i-1]);
		if (i % 5 == 0)		// 每输出5个数 换行
			printf("\n");
	}
	return 0;
}

5. Randomly generate n unordered random numbers in the range of [-10,10], store them in an array and display the results, delete the same number in the array until only one remains, and output the deleted results

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int n;
	printf("输入n:\n");
	scanf("%d", &n);
	int a[n], t;
	printf("原数组:\n");
	for (int i = 0; i < n; i++) {
    
    
		a[i] = -10 + rand() % 21;	// rand()%21生成数的范围[0,20],-10后范围即[-10,10]
		printf("%d\n", a[i]);		// 显示原数组
	}
	// 删除数组中重复的数
	for (int i = 0; i < n; i++)		// 循环判断数组中每一个数
		for (int j = i + 1; j < n; j++)
			if (a[i] == a[j]) {
    
    		// 判断a[i]后边的数是否和a[i]相等
				for (t = j; t < n - 1; t++)
					a[t] = a[t + 1];	// 将a[j]后面的元素全往前移一个位置,将重复的a[j]覆盖
				j--;	// a[j+1]取代a[j]位置,为使下次从a[j+1]开始查找,j-1使j保持不变
				n--;	// 数组长度减一
			}
	printf("删除重复后:\n");
	for (int i = 0; i < n; i++)
		printf("%d\n", a[i]);	// 打印去重后的数组
	return 0;
}

6. Find the highest and lowest grades and the number of people with higher than average grades in a course of n students

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int n;
	printf("输入n:\n");
	scanf("%d", &n);
	int a[n], t, s = 0, count = 0;
	printf("%d名学生的成绩为:\n", n);
	for (int i = 0; i < n; i++) {
    
    
		a[i] =  rand() % 101;	// 随机生成0-100分成绩
		s += a[i];				// 计算成绩总和,求平均成绩
		printf("%d\n", a[i]);
	}
	for (int i = 0; i <= n - 2; i++)	//	冒泡排序
		for (int j = 0; j <= n - 2 - i; j++)
			if (a[j] < a[j + 1]) {
    
    
				t = a[j];
				a[j] = a[j + 1];
				a[j + 1] = t; 
			}
	for (int i = 0; i < n; i++)
		if (a[i] > (float)s / n) count++;	// 计算高于平均成绩的人数
	printf("最高成绩:%d\n", a[0]);
	printf("最低成绩:%d\n", a[n - 1]);
	printf("平均成绩:%f\n", (float)s / n);
	printf("高于平均:%d", count);
	return 0;
}

7. Use an array to find the first 20 items of the following sequence

0,1,1,2,4,7,13
三数版肥波纳气数列

#include <stdio.h>
int main() {
    
    
	int a[20] = {
    
    0, 1, 1};	// 0,1,1,2,4,7,13,...每一项为前三项之和
	printf("0\n1\n1\n");	// 先输出前3项
	for (int i = 3; i < 20; i++) {
    
    	// 再从数组第4项开始循环,分别输出每一项
		a[i] = a[i - 1] + a[i - 2] + a[i - 3];
		printf("%d\n", a[i]);
	}
	return 0;
}

8. Place a one-bit array in reverse order

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int n;	// 数组中元素个数n
	scanf("%d", &n);
	int a[n], b[n];
	for (int i = 0; i < n; i++) {
    
    
		a[i] = rand();	// 随机生成数组a
		b[n - 1 - i] = a[i];	// 数组b从后往前依次等于数组a从前往后
	}

	printf("a=(");
	for (int i = 0; i < n; i++)
		printf("%d,", a[i]);	// 输出a数组
	printf("\b)\n");	// 删除前面的逗号
	printf("反序放置后:\na=(");
	for (int i = 0; i < n; i++)
		printf("%d,", b[i]);	// 输出b数组
	printf("\b)\n");
	return 0;
}

8. Experiment 8: Array (2)

1. Put the element values ​​in a one-bit array a[9] into the two-dimensional array b[3×3] in the order of rows

#include <stdio.h>
int main() {
    
    
	int a[9] = {
    
    0, 1, 2, 3, 4, 5, 6, 7, 8}, b[3][3];
	for (int i = 0; i < 3; i++) {
    
    
		for (int j = 0; j < 3; j++) {
    
    
			b[i][j] = a[i * 3 + j];		// b矩阵中的元素(行×3+列)为在a数组中位置
			printf("%d\t", b[i][j]);	// 显示二维数组b
		}
		printf("\n");
	}
	return 0;
}

2. Output n×n digital square matrix

#include <stdio.h>
int main() {
    
    
	int n;
	scanf("%d", &n);
	int a[n][n];
	for (int i = 0; i < n; i++) {
    
    	// n行
		for (int j = 0; j < n; j++) {
    
    	// n列
			a[i][j] = (i + 1) * (j + 1); // 每个元素值为行数×列数
			printf("%d\t", a[i][j]);
		}
		printf("\n");
	}
	return 0;
}

3. Set the elements on the diagonal of the square matrix m(n,n) to 1, and the remaining elements to 0

#include <stdio.h>
int main() {
    
    
	int n;
	scanf("%d", &n);
	int m[n][n];
	for (int i = 0; i < n; i++) {
    
    
		for (int j = 0; j < n; j++) {
    
    
			if (i == j || i + j == n - 1) m[i][j] = 1;
			// i=j时为主对角线上的元素,i+j=n-1为副对角线上元素
			else m[i][j] = 0;			// 其余元素为0
			printf("%d\t", m[i][j]);
		}
		printf("\n");
	}
	return 0;
}

4. There is an m×n matrix, each element value is generated by a random number, add a column to the matrix, find the sum of the element values ​​of each row of the matrix, and put the sum into the added column, and display the result

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int n, m;
	scanf("%d%d", &m, &n);
	int a[m][n + 1];	// 矩阵增加一列
	for (int i = 0; i < m; i++) {
    
    
		int s = 0;
		for (int j = 0; j < n; j++) {
    
    
			a[i][j] = rand();	// 生成随机值
			s += a[i][j];	// 计算当前行元素和
		}
		a[i][n] = s;		//将元素和放入最后一列
	}
	for (int i = 0; i < m; i++) {
    
    	//输出矩阵
		for (int j = 0; j < n + 1; j++)
			printf("%d\t", a[i][j]);
		printf("\n");
	}
	return 0;
}

5. There is an m×n matrix, find the maximum element value and the row and column position of the maximum element value

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	srand(time(NULL));
	int m, n;
	scanf("%d%d", &m, &n);
	int a[m][n], max = 0;
	
	/*for (int i = 0; i < m; i++)	//	手动输入元素
		for (int j = 0; j < n; j++)
			scanf("%d", &a[i][j]);*/

	for (int i = 0; i < m; i++)		//  随机生成元素
		for (int j = 0; j < n; j++)
			a[i][j] = rand();
			
	/*for (int i = 0; i < m; i++) { // 打印矩阵检查
		for (int j = 0; j < n; j++)
			printf("%d\t", a[i][j]);
		printf("\n");
	}*/
	
	for (int i = 0; i < m; i++)		//  找出矩阵中最大值
		for (int j = 0; j < n; j++)
			if (a[i][j] > max)
				max = a[i][j];
	printf("最大值为%d\n在", max);
	for (int i = 0; i < m; i++)		//  找出最大值位置
		for (int j = 0; j < n; j++)
			if (a[i][j] == max)
				printf("第%d行 第%d列\n", i + 1, j + 1);
	return 0;
}

6. There are n candidates, and each candidate has a test number and a total score. If m people are admitted, the admission score line is determined, and the candidate's test number and score are output

#include <stdio.h>
int main() {
    
    
	int n, m;
	printf("考生人数:");
	scanf("%d", &n);
	printf("录取人数:");
	scanf("%d", &m);
	int a[n][2], t, p;	// 定义n行2列数组,第一列为考号,第二列为成绩
	for (int i = 0; i < n; i++) {
    
    	// 录入成绩
		printf("输入考号:");
		scanf("%d", &a[i][0]);
		printf("输入考号:%d 的考生成绩:", a[i][0]);
		scanf("%d", &a[i][1]);
	}
	for (int i = 0; i < n - 1; i++)		// 冒泡法成绩排序
		for (int j = 0; j <= n - 2 - i; j++)
			if (a[j][1] < a[j + 1][1]) {
    
    
				t = a[j][1];
				a[j][1] = a[j + 1][1];
				a[j + 1][1] = t;        // 按成绩排序
				p = a[j][0];
				a[j][0] = a[j + 1][0];
				a[j + 1][0] = p;        // 排序成绩对应的考号
			}
	/*	for (int i = 0; i < n; i++)
			for (int j = 0; j < 2; j++)
				printf("%d\t", a[i][j]);    //打印排序后成绩
			printf("\n");*/

	printf("录取分数线为:%d\n", a[m - 1][1]);
	printf("录取考生为:");
	for (int i = 0; i < m; i++) {
    
    
		printf("考号:%d\t", a[i][0]);
		printf("成绩:%d\n", a[i][1]);
	}
	return 0;
}

It only says to admit m people, so it is not considered to be tied, and the one with the smaller test number will be admitted according to the parallel, the fate is so unpredictable


9. Experiment 9: Function

1. Use the function process to calculate n ! m ! ( n − m ) ! n! \over m!(nm)!m!(nm)!n!

#include <stdio.h>
int fact(int n) {
    
    	// 计算阶乘
	if (n < 0)
		return 0;
	if (n == 0 || n == 1)	// 0和1的阶乘为1
		return 1;
	else
		return n * fact(n - 1); // 递归
}
int main() {
    
    
	int n, m;
	scanf("%d%d", &n, &m);
	printf("%d", fact(n) / fact(m) / fact(n - m));
	return 0;
}

2. Write the function procedure and calculate: 1 ! + 2 + 3 ! + ⋯ + 10 ! 1!+2+3!+\cdots+10!1!+2+3!++10!

#include <stdio.h>
int fact(int n) {
    
      	// 又是阶乘,直接抄
	if (n < 0)
		return 0;
	if (n == 0 || n == 1)
		return 1;
	else
		return n * fact(n - 1);	
}
int main() {
    
    
	int s = 0;
	for (int i = 1; i <= 10; i++)
		s += fact(i);
	printf("%d", s);
}

3. Determine whether a number is a palindrome

回文数:指对称位置的数字相同,如121,12321

#include <stdio.h>
#include <string.h>
void palindrome(char c[]) {
    
    
	int len, flag = 1;
	len = strlen(c);	// strlen获取输入字符串的长度
	for (int i = 0; i <= len / 2; i++)
		if (c[i] != c[len - 1 - i]) {
    
    
			flag = 0;	// 从左右两端依次向内判断字符是否相同,不同则不是回文数,结束循环
			break;
		}
	if (flag == 1)
		printf("是回文数\n");
	else
		printf("不是回文数\n");
}
int main() {
    
    
	char a[100];
	gets(a);
	palindrome(a);
	return 0;
}

4. Write the function process to find the Feibo Naqi sequence

(1) The first n items and FS
(2) The average V of the first n items
and calculate and output FS and the famous V for n=20

#include <stdio.h>
int FS(int n) {
    
    	// 求斐波那契数列前n项和
	int f1 = 1, f2 = 2, f3, s = 2;
	if (n == 0) return 0;
	else if (n == 1) return 1;		// 前1项和为1
	else if (n == 2) return 2;		// 前2项和为2
	else {
    
    
		for (int i = 3; i <= n; i++) {
    
    
			f3 = f1 + f2;
			f1 = f2;
			f2 = f3;
			s += f3;
		}
		return s;
	}
}
double V(int n){
    
    	// 求前n项平均值
	double v;
	v=FS(n)/(float)n;
	return v;
}
int main(){
    
    
	int n;
	scanf("%d",&n);
	printf("前n%d和为%d\n",n,FS(n));
	printf("前n%d平均值为%f\n",n,V(n));
	return 0;
}

5. Write a one-variable function f ( x ) f(x) using the trapezoidal methodf ( x ) in( a , b ) (a,b)(a,b ) Functional process of the upper integral approximation. andf ( x ) = sin ( 2 x ) + xf(x)=sin(2x)+xf(x)=s i n ( 2 x )+x , at[ a , b ] = [ 0 , 3.14159 ] [a,b]=[0,3.14159][a,b]=[0,3 . 1 4 1 5 9 ] , when the number of cell intervals is n=10 and n=20, calculate and output the approximate values ​​s1 and s2 of the integral respectively, retaining three decimal places

#include <stdio.h>
#include <math.h>
#define pi 3.14159
#define f(x) sin(2*x*pi/180)+x	// 将x转为弧度制
double integral(double x1, double x2, int n) {
    
    	// x1,x2为积分上下限,n为分成的梯形小区间个数
	double s = 0, b1, b2, h;
	h = (x2 - x1) / n;
	for (int i = 0; i < n; i++) {
    
    
		b1 = f(x1 + i * h);		//b1,b2为梯形上下底,即小区间左右端点对应函数值
		b2 = f(x1 + (i + 1) * h);
		s += (b1 + b2) * h / 2;	//将所有梯形面积相加为积分近似值
	}
	return s;
}
int main() {
    
    
	double x1 = 0, x2 = pi, s1, s2;
	int n1 = 10, n2 = 20;
	s1 = integral(x1, x2, n1);
	s2 = integral(x1, x2, n2);
	printf("s1=%.3f\ns2=%.3f\n",s1, s2);
}

6. Find the number of numeric characters in any string CH

#include <stdio.h>
#include <string.h>
char CH(char c[]) {
    
    
	int count = 0;	// 计数
	for (int i = 0; i < (int)strlen(c); i++)
		if (c[i] >= '0' && c[i] <= '9')	//数字ASCII码在0-9之间
			count++;
	return count;	//返回计数器
}
int main() {
    
    
	char c[100] = {
    
    0};
	gets(c);
	CH(c);
	printf("%d", CH(c));
	return 0;
}

7. Find the greatest common divisor and least common multiple of two positive integers

#include <stdio.h>
int dvi(int m, int n) {
    
     // 辗转相除法 求最大公约数
	int r;
	r = m % n;
	while (r != 0) {
    
    
		m = n;
		n = r;
		r = m % n;
	}
	return n;
}
int main() {
    
    
	int m, n;
	scanf("%d%d", &m, &n);
	printf("最大公约数:%d\n", dvi(m, n));
	printf("最小公倍数:%d\n", m * n / dvi(m, n)); // 乘积除以最大公约数得到最小公倍数
	return 0;
}

8. Write a function process to solve the quadratic equation ax 2 + bx + c = 0 ax^2+bx+c=0ax2+bx+c=0

Requirements: a, b, c and the solution x1, x2 all exchange data with the calling process in the form of parameters

#include <stdio.h>
#include <math.h>
int Equation(double a, double b, double c, double *x1, double *x2) {
    
     
// 用x1,x2的指针作为参数,在函数调用过程中计算x1,x2,根据返回值的不同判断x1,x2作为什么类型的根
	double  D = pow(b, 2) - 4 * a * c;
	if (a == 0) {
    
    		    // 当a=0时按一次方程求解
		if (b == 0) {
    
          // 当b也等于0时,方程无解
			return 0;     // 返回0 无解
		}
		*x1 = -c / b;
		*x2 = *x1;
		return 1;        // 返回1,一次方程只有一个解
	}
	if (D >= 0) {
    
    
		*x1 = (-1.0 * b + sqrt(D)) / 2 * a;
		*x2 = (-1.0 * b - sqrt(D)) / 2 * a;
		return 2;        // 返回2,两个解
	} else {
    
    
		*x1 = -1.0 * b / 2 * a;		// 共轭复根实部
		*x2 = sqrt(-1.0 * D) / 2 * a;	// 共轭复根虚部
		return -1;       // 返回-1,无实数解,得两个共轭复根
	}
}
int main() {
    
    
	double a, b, c, x1, x2;
	scanf("%lf%lf%lf", &a, &b, &c);
	int r = Equation(a, b, c, &x1, &x2);
	if (r == 0)
		printf("a, b都为0,方程无解\n");
	else if (r == 1)
		printf("a = 0为一次方程\nx = %.3f\n", x1);
	else if (r == 2)
		printf("方程有两个实数解\nx1 = %.3f\nx2 = %.3f\n", x1, x2);
	else if (r == -1)
		printf("方程无实数解\nx1 = %.3f + %.3fi\nx2 = %.3f - %.3fi", x1, x2, x1, x2);
	return 0;
}

9. Use the Newton iteration method to find the equation x 5 + 2 x 3 − x 2 + x + 1 = 0 x^5+2x^3-x^2+x+1=0x5+2x _3x2+x+1=0 in0 0Approximate value around 0

#include <stdio.h>
#include <math.h>
#define f(x) pow(x,5)+2*pow(x,3)-pow(x,2)+x+1  
#define d(x) 5*pow(x,4)+6*pow(x,2)-2*x+1	//定义f(x)和f'(x)

double newton(double x) {
    
    
	double fx, dx, delta_x = f(x) / d(x);	// 计算△x
	while (fabs(delta_x) > 1e-6) {
    
    	// △x<1e-6时退出循环
		x -= delta_x; 	// 更新x
		fx = f(x);
		dx = d(x);
		delta_x = fx / dx;	// 更新△x
	}
	return x;
}

int main() {
    
    
	printf("%f\n", newton(0));
	return 0;
}

10. Calculate the sum of all prime numbers between positive integers n1~n2

#include <stdio.h>
#include <math.h>
int Primes(int n1, int n2) {
    
    
	int sum = 0, k, j;
	for (int i = n1; i <= n2; i++) {
    
    
		if (i == 1) // 如果n1 = 1,跳过
			i++;
		k = sqrt(i);
		for (j = 2; j <= k; j++)
			if (i % j == 0)
				break;
		//如果i能被比他开方值小的数整除,他不是素数,则退出循环
		if (j > k)
			// 当循环结束之后还没有被整除,为素数
			sum += i;
	}
	return sum;
}
int main() {
    
    
	int n1, n2;
	scanf("%d%d", &n1, &n2);
	printf("%d\n", Primes(n1, n2));
	return 0;
}

*10. Use the recursive method to find the sum of the first 20 items of Feibo Naqi sequence and the sum of these 20 items

#include <stdio.h>
#include <math.h>

int Fibonacci(int n) {
    
    	// 递归函数,计算第n项斐波那契数列的值
	if (n <= 0)
		return 0;
	else if (n == 1)
		return 1;
	else
		return Fibonacci(n - 1) + Fibonacci(n - 2);
}
int main() {
    
    
	int s = 0;
	printf("前20项为:\n");
	for (int i = 1; i <= 20; i++) {
    
    
		printf("%d\n", Fibonacci(i));	// 输出第i项斐波那契数列的值
		s += Fibonacci(i);	 // 累加前i项斐波那契数列的和
	}
	printf("和为:%d\n", s);
	return 0;
}

10. Experiment 10: Compilation preprocessing

1. Design a macro with parameters to judge odd numbers, read integers continuously in the main function, and terminate the program until the input integer is odd

#include <stdio.h>
#define odd(n) n % 2 == 0	// 定义带参宏,当n%2为0时,返回值为TURE,否则为FALSE
int main() {
    
    
	int n;
	do {
    
    
		scanf("%d", &n); // 连续读取输入整数n
	} while (odd(n)); // 当输入n为偶数时继续,为奇数时退出循环
	printf("%d是奇数\n", n);
	return 0;
}

2. Use a macro with parameters to realize the function of finding the maximum value of two numbers, and then use the above-mentioned macro with parameters to design a macro with parameters to find the largest number among three numbers. In the main function, find the maximum value in the following form of data

(1) (a,b) (2) (a,b,c) (3) (a-2,b+2) (4) (a-2,b,c+2)

#include <stdio.h>
#define max_two(a, b) (a > b) ? a : b
// 判断,若a>b,返回a,否则返回b
#define max_three(a, b, c) (max_two(a, b) > c) ? max_two(a, b) : c
//  判断a,b两者最大值和c的大小
int main() {
    
    
	float a, b, c;
	scanf("%f%f%f", &a, &b, &c);
	printf("%f\n", max_two(a, b));
	printf("%f\n", max_three(a, b, c));
	printf("%f\n", max_two(a - 2, b + 2));
	printf("%f\n", max_three(a - 2, b, c + 2));
	return 0;
}

3. Enter two integers and find the remainder of their division. Use macros with parameters to implement, and write the main function call macro.

#include <stdio.h>
#define mod(a, b) a % b
// 输入a,b,返回a%b
int main() {
    
    
	int a, b;
	scanf("%d%d", &a, &b);
	printf("%d\n", mod(a, b));
	return 0;
}

4. Define a macro for the year to determine whether the year is a leap year, and write the main function call macro.

#include <stdio.h>
#define Leap(year) (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
// 判断是否闰年,是闰年则返回True,否则返回False
int main() {
    
    
	int year;
	scanf("%d", &year);
	if (Leap(year))
		printf("%d是闰年\n", year);
	else
		printf("%d不是闰年\n", year);
	return 0;
}

5. The area of ​​the triangle is: area = s ( s − a ) ( s − b ) ( s − c ) area= \sqrt{s(sa)(sb)(sc)}area=s(sa)(sb)(sc) , where s = 1 2 ( a + b + c ) s=\frac{1}{2} (a+b+c)s=21(a+b+c), a , b , c a,b,c a,b,c is the three sides of the triangle. Define two macros with parameters, one is used to findsss , the other is used to findarea areaa r e a , use the macro name with actual parameters to calculate the areaarea areaarea

#include <stdio.h>
#include <math.h>
#define s(a, b, c) 1.0 / 2 * (a + b + c)	// 求s
#define area(s, a, b, c) sqrt(s * (s - a) * (s - b) * (s - c))	// 求area
int main() {
    
    
	double a, b, c, s;
	scanf("%lf%lf%lf", &a, &b, &c);
	s = s(a, b, c);
	printf("%f\n", area(s, a, b, c));
	return 0;
}

11. Experiment 11: Pointer

1. Use pointer variables to output three integers in ascending order

#include <stdio.h>
int main() {
    
    
	void sort(int *p, int *q);	// 声明排序函数
	int a, b, c;
	scanf("%d%d%d", &a, &b, &c);
	sort(&a, &b);		// 将a,b,c的地址输入函数进行排序
	sort(&a, &c);
	sort(&b, &c);
	printf("%d %d %d", a, b, c);
	return 0;
}
void sort(int *p, int *q) {
    
    
	int temp;		// 定义临时变量
	if (*p > *q) {
    
    	// 如果指针p地址中的值大于q的,交换p和q地址中的值
		temp = *p;
		*p = *q;
		*q = temp;
	}
}

2. Input n (not greater than 20) single-precision numbers and store them in a one-bit array, use pointer variables to process array elements, store them in reverse order and output

#include <stdio.h>
int main() {
    
    
	int n;
	scanf("%d", &n);	// 输入数组位数n
	
	float a[n], re_a[n], *p = &a[n - 1];	// 定义指针p为数组a的最后一个元素
	
	for(int i=0;i<n;i++)
		scanf("%f",&a[i]);			// 输入数组a的元素
		
	for (int i = 0; i < n; i++) {
    
    
		re_a[i] = *p--;		// 将指针指向的最后一个元素存入数组re_a中,完成将数组a逆序存放,并将指针向前移动一位
		printf("%f\n", re_a[i]);	// 输出逆序存放的元素
	}
	return 0;
}

3. Use pointers to complete the exchange of two variable values

#include <stdio.h>
int main() {
    
    
	int a = 1, b = 2, t;
	int *p = &a, *q = &b;
	t = *p;		// 用临时变量存放a的值
	*p = *q;	// 将b的值赋给a
	*q = t;		// 将临时变量中a的值赋给b
	printf("%d %d", a, b);
	return 0;
}

4. Write a program to initialize an array of character pointers with the English names of December. When the keyboard enters an integer 1-12, the corresponding month name will be displayed, and an error message will be displayed when other integers are entered.

#include <stdio.h>
int main() {
    
    
	char *months[] = {
    
    "January", "February", "March", "April", "May", "June",
	                  "July", "August", "September", "October", "November", "December"
	                 }; // 定义字符指针数组
	int n;
	scanf("%d", &n);	   // 输入月份数
	if (n >= 1 && n <= 12) // 判断输入是否正确
		printf("%s\n", months[n - 1]);
	else
		printf("Error\n");
	return 0;
}

5. Use the selection method to sort 10 integers (descending order)

#include <stdio.h>
int main() {
    
    
	int a[10] = {
    
    3, 7, 6, 4, 9, 5, 6, 2, 7, 4}, j, m, t;
	int *p = a; // 定义指针p指向数组a的首地址
	for (int i = 0; i < 9; i++) {
    
    
		// 选择法排序
		m = i; // m表示未排序序列中最大的数的索引
		for (j = i + 1; j < 10; j++)
			// 在未排序序列中找最大的数
			if (*(p + m) > *(p + j))
				m = j;
		if (m != i) {
    
    
			// 将最大的数与当前的数交换位置
			t = *(p + i);
			*(p + i) = *(p + m);
			*(p + m) = t;
		}
	}
	for (int i = 0; i < 10; i++, p++)
		printf("%d\n", *p); // 输出排序后数列
	return 0;
}

6. Write a program to input a string of symbols from the keyboard (terminated by the Enter key), store it in a one-dimensional character array in the form of a string, and then output the string of the character array

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char a[100];
	fgets(a,100,stdin);  // 获取键盘输入并存入数组
	puts(a); // 输出该数组中的字符串
	return 0;
}

7. Write a program to calculate the length of a string

#include <stdio.h>
#include <string.h>
int main()
{
    
    
	char a[100];
	gets(a);				 // 键盘输入字符串
	int cnt = 0;			 // 计数器
	while (a[cnt] != '\0') // 当读取到末尾标记时结束循环
		cnt++;
	printf("%d\n", cnt);
	printf("%d\n", strlen(a)); // 直接用strlen计算字符串长度
	return 0;
}

8. Write a program to count the number of occurrences of a substring in a string, and return 0 if the character does not appear

#include <stdio.h>
#include <string.h>
int main() {
    
    
	int substr(char*, char*);
	char str[100], sub[100];
	gets(str);		// 输入字符串
	gets(sub);		// 输入子字符串
	int num = substr(str, sub);	// 调用函数计算出现次数
	printf("%d", num);
	return 0;
}

int substr(char *str, char *substr) {
    
    	// 计算子字符串出现次数
	int count = 0;
	while (*str != '\0') {
    
    // 当读取到字符串末尾时退出循环
		char *p1 = str, *p2 = substr;	// 定义指针指向字符串首地址
		while (*p2 != '\0' && *p1 == *p2) {
    
    
			// 当子字符串指针p2没有移动到末尾时,与原字符串指针取的值相等,
			// 即表示子字符串有字符和原字符串相等, 指针依次后移继续判断下一位是否相等
			p1++;
			p2++;
		}
		if (*p2 == '\0')	// 若子字符串指针移动到了末尾,即说明上一步完整循环了子字符串,子字符串在原字符串中出现了一次	
			count++;
		str++;	// 原字符串后移,从下一位继续判断子字符串是否出现
	}
	return count;
}

12. Experiment 12: Structure and Union

About long long:
vc6.0用 __int64定义,%I64d输出
Image source: Comparison of different compilation environments between long long and __int64 under c/c++   Author: Violet-Guo

1. Set the student information as follows: student number (long integer), name (string type), age (integer), course 1-7 grades (real type), total score (real type), average score (real type ). Write a program, input the above information of 3 students, calculate the total score and average score of each student, and then output the student number, name, total score, and average score

#include <stdio.h>
struct Student {
    
    
	// 定义结构体
	long long ID;	// 学号  vc6.0改为__int64 ID;
	char name[20];	// 姓名
	int age;		// 年龄
	double course[7];	// 7门课程成绩
	double total, average;	// 总成绩,平均成绩
};
int main() {
    
    
	struct Student s[3];	// 创建名为s的结构体数组,分别存储3名学生的信息
	for (int i = 0; i < 3; i++) {
    
    
		s[i].total = 0;		// 初始化总成绩
		printf("输入第%d名学生的:学号  姓名  年龄\n",  i + 1);
		scanf("%I64d %s %d", &s[i].ID, s[i].name, &s[i].age);	// 循环输入学号姓名年龄
		for (int j = 0; j < 7; j++) {
    
    	// 循环输入7门课程成绩
			printf("输入该学生课程%d成绩: ", j + 1);
			scanf("%lf", &s[i].course[j]);
			s[i].total += s[i].course[j];	// 成绩加和计算总成绩
		}
		s[i].average = s[i].total / 7;		// 计算平均成绩
	}
	// 输出学生信息表格
	printf("%-14s%-10s%-8s%-7s\n", "学号", "姓名", "总分","平均分");
	// 左对齐输出 学号等字符串,并对其输出学生信息内容
	for (int i = 0; i < 3; i++)	
		printf("%-14I64d%-10s%-8.2f%-7.2f\n", s[i].ID, s[i].name, s[i].total, s[i].average);	
	return 0;
}

2. The student information is set as follows: student number (long integer), name (string type), date of birth (including the year, month, and day are integers). Enter the above information for 5 students, and output the student ID, name and age of all students

#include <stdio.h>
#include <time.h>
#include <windows.h>

struct Student {
    
    
	// 定义结构体学生
	long long ID;	// 长整型学号(__int64)
	char name[20];	// 姓名
	int year, month, day, age;	// 出生年月日和年龄
};
int main() {
    
    
	SYSTEMTIME sys;	// 定义结构体变量名
	GetLocalTime(&sys);	// 获取系统时间,计算当前年龄

	struct Student s[5];	// 定义学生结构体数组,表示5个学生的信息
	for (int i = 0; i < 1; i++) {
    
    
		printf("请输入第%d名学生的学号和姓名:\n", i + 1);
		scanf("%I64d%s", &s[i].ID, s[i].name);	// 输入学生的学号姓名
		printf("请输入%s的出生年月日:(yyyy-mm-dd)\n", s[i].name);
		scanf("%d-%d-%d", &s[i].year, &s[i].month, &s[i].day);	// 输入出生年月日以-分隔
		s[i].age = sys.wYear - s[i].year;		// 生日比当前日期小
		if ((s[i].month == sys.wMonth && s[i].day > sys.wDay) || s[i].month > sys.wMonth )
			s[i].age--;						// 如果生日比当前日期大,年龄-1
		else if (s[i].year > sys.wYear || (s[i].year == sys.wYear && s[i].month > sys.wMonth) || (s[i].year == sys.wYear && s[i].month == sys.wMonth && s[i].day > sys.wDay))
			s[i].age = 0;		// 输入的日期大于当前日期,年龄无效输出0
	}
	printf("%-14s%-10s%-3s\n", "学号","姓名","年龄");
	for (int j = 0; j < 5; j++)		// 输入学生信息
		printf("%-14I64d%-10s%-3d\n", s[j].ID, s[j].name, s[j].age);
	return 0;
}

3. Output the system date in the format of "year/month/day", and output the system time in the format of "hour:minute:second.XX"

#include <stdio.h>
#include <windows.h>
int main() {
    
    
	SYSTEMTIME sys;	// 定义结构体变量名
	GetLocalTime(&sys);	// 获取系统时间
	printf("%d/%02d/%02d\t", sys.wYear, sys.wMonth, sys.wDay);	// 输出系统时间日期,宽2位不足用0补齐
	printf("%02d:%02d:%02d.%02d", sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds);
	return 0;
}

4. There are several personnel data, including teachers and students. The student's data includes: name, number, gender, occupation, class. The teacher's data includes: name, number, gender, occupation, position. Requires related person data to be entered and then output.

#include <stdio.h>
#include <string.h>
struct person {
    
    	// 学生和教师共有的结构体成员
	char name[20];	// 姓名
	long long num;	// 号码
	char gen[10];	// 性别
};

struct student {
    
    
	struct person p;
	char cla[20];	// 学生班级
};

struct teacher {
    
    
	struct person p;
	char pos[20];	// 教师职务
};

int main() {
    
    
	struct student s[100];	// 建立学生结构体数组,存放学生数据
	struct teacher t[100];	// 建立教师结构体数组,存放教师数据
	char m[10], n;	// 数组m存储输入的职业,判断学生还是教师
	int i_s = 0, i_t = 0;	// 学生和教师的数组索引
	for (int i = 0; i < 100; i++) {
    
    
		printf("请选择录入人员职业(学生/教师)\n");
		scanf("%s", m);
		if (strcmp(m, "学生") == 0) {
    
    	// 比较输入的字符串是否与"学生"相等
			printf("请输入姓名,号码,性别和班级:\n");
			scanf("%s%I64d%s%s", s[i_s].p.name, &s[i_s].p.num, s[i_s].p.gen, s[i_s].cla);
			// 录入学生信息
			i_s++;
		} else if (strcmp(m, "教师") == 0) {
    
    
			printf("请输入姓名,号码,性别和职务:\n");
			scanf("%s%I64d%s%s", t[i_t].p.name, &t[i_t].p.num, t[i_t].p.gen, t[i_t].pos);
			// 录入教师信息
			i_t++;
		} else {
    
    
			printf("输入错误\n");	// 输入错误i退回
			i--;
		}
		printf("是否继续录入?(Y/N)\n");
loop:
		fflush(stdin);	// 清空输入缓冲区
		scanf("%c", &n);
		if (n == 'Y' || n == 'y')
			continue;	// 输入y则跳过当前循环开始下一次循环
		else if (n == 'N' || n == 'n')
			break;		// 输入n则结束循环输出信息
		else {
    
    
			printf("输入有误(Y/N)\n");
			goto loop;	// 输入有误则回到loop重新输入
		}
	}
	
	printf("学生信息:\n");
	printf("%-10s%-12s%-6s%s\n", "姓名", "号码", "性别", "班级");
	for (int j = 0; j < i_s; j++)
		printf("%-10s%-12I64d%-6s%s\n", s[j].p.name, s[j].p.num, s[j].p.gen, s[j].cla);
		// 输出学生信息
	printf("\n教师信息:\n");
	printf("%-10s%-12s%-6s%s\n", "姓名", "号码", "性别", "职务");
	for (int j = 0; j < i_t; j++)
		printf("%-10s%-12I64d%-6s%s\n", t[j].p.name, t[j].p.num, t[j].p.gen, t[j].pos);
		// 输出教师信息
	return 0;
}

5. Knowing the student ID, name, gender and age of three students, it is required to send the data to a structure variable through direct assignment, and then output

#include <stdio.h>
#include <string.h>
struct Student {
    
    	// 定义结构体
	long long ID;
	char name[20];
	char gender[3];
	int age;
};
int main() {
    
    
	struct Student s[3];
	char names[][20]={
    
    "张三","李四","王二麻子"};	// 姓名
	char genders[][3]={
    
    "男","男","男"};	// 性别
	printf("%-5s%-10s%-5s%s\n","学号","姓名","性别","年龄");
	for (int i = 0; i < 3; i++) {
    
    
		s[i].ID = i + 1;	// 学号为序号
		strncpy(s[i].name,names[i],sizeof(s[i].name));	// 将数组中的元素赋给结构体变量
		strncpy(s[i].gender,genders[i],sizeof(s[i].gender));
		s[i].age = 18+i;
		printf("%-5I64d%-10s%-5s%d\n",s[i].ID,s[i].name,s[i].gender,s[i].age);	// 输出
	}
	return 0;
}

13. Experiment 13: Documentation

1. Use text editing software to create a data file on the disk with the student numbers, names and grades of n students in three courses: English, Mathematics and Computer

Right-click -> New -> Text Document
file storage format
(the next question reads the file content according to this format)
input data -> file in the upper left corner -> save as -> encoding select ANSI -> save
(I use UTF-8 encoding to output Chinese Sometimes it will be garbled)
insert image description here

2. Read the data file created in the first question and find the average score of each student

#include <stdio.h>
#include <stdlib.h>
struct Student {
    
    	// 建立结构体用来存储数据
	long long ID;	// 学号
	char name[20];	// 姓名
	double English, math, computer, sum, avg;	// 各科,总,平均成绩
};
int main() {
    
    
	struct Student s[100];	// 定义结构体数组
	FILE *fp = fopen("13-1.txt", "r");	// 打开文件并让指针指向文件
	if (!fp) {
    
     // 如果失败
		perror("qvq文件打开失败");	// 用于显示错误信息
		exit(0); // 退出程序
	}
	char f[100];	// 每行输入储存的数组
	int i = 0;
	printf("%-14s%-10s%-8s\n", "学号", "姓名", "平均成绩");
	while (fgets(f, 200, fp) != NULL) {
    
    
		sscanf(f, "%I64d%s%lf%lf%lf", &s[i].ID, s[i].name, &s[i].English, &s[i].math, &s[i].computer);
		// 把文件中的数据存入结构体数组
		s[i].sum = s[i].English + s[i].math + s[i].computer;
		s[i].avg = s[i].sum / 3;	// 计算平均成绩
		printf("%-14I64d%-10s%-6.2f\n", s[i].ID, s[i].name, s[i].avg);	// 输出
		i++;	// 循环下一行
	}
	fclose(fp);// 关闭文件
	return 0;
}

3. Write a program to merge the two text files on the disk into the first text file

To create two new files for merging

#include <stdio.h>
#include <stdlib.h>
int main() {
    
    
	FILE *fpa, *fpb, *fpc;
	char ch;
	fpa = fopen("13-3-1.txt", "r"); // 打开文件1,注意三个文件编码格式要相同
	fpb = fopen("13-3-2.txt", "r");	// 打开文件2
	fpc = fopen("13-1.txt", "a+");	// 打开合并后的文件,"a"为追加,将文件1,2内容追加文件中,若要清除文件内原有内容重新写入,改为"w"
	if (!fpa || !fpb || !fpc) {
    
    
		perror("qwq文件打开失败");
		exit(0);		// 如果打开失败退出程序
	}
	fprintf(fpc,"\n");
	while ((ch = fgetc(fpa)) != EOF)
		fputc(ch, fpc);		// 写入1文件内容
	while ((ch = fgetc(fpb)) != EOF)
		fputc(ch, fpc);		// 写入2文件内容
	printf("^o^文件合并成功\n");
	fclose(fpc);
	fclose(fpb);
	fclose(fpa);
	return 0;
}

4. Copy the program created in question 3

#include <stdio.h>
#include <stdlib.h>
int main() {
    
    
	char ch;
	FILE* fp1 = fopen("13-3.c", "r");	// 打开第三题程序
	FILE* fp2 = fopen("copy13-3.c", "w");	// 复制的第三题文件命名为copy13-3
	if (!fp1 || !fp2)
		perror("qaq文件打开失败");
		exit(0);
	while ((ch = fgetc(fp1)) != EOF)	// 循环读取直到结束
		fputc(ch, fp2);		// 将内容写入副本中
	printf("程序复制成功!(′ヮ`)");
	fclose(fp1);	// 关闭文件
	fclose(fp2);
	return 0;
}

5. Use the method of generating random numbers to generate: the serial numbers of 100 shopping malls (between 1 and 500), the sales amount of each shopping mall in each of the four quarters of the year (unit ten thousand yuan), and store these data in the data file , and then use this file to find the total sales amount of each shopping mall for one year.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
struct MALL {
    
    	// 商场结构体
	int id;	// 商场编号
	double q1, q2, q3, q4;	// 四个季度营业额
	double sum;		// 营业总额
};

int cmp(const void *a, const void *b) {
    
    
	return *(int*)a - *(int*)b;
}	// qsort比较函数

int main() {
    
    
	srand((unsigned int)time(NULL));
	struct MALL m[100];
	int a[100], k = 0, j, r;	// a数组储存商场编号
	while (k < 100) {
    
    	// 生成100个不重复的随机数
		r = rand() % 500 + 1;	//生成一个1-500的随机数,临时存放在r
		Sleep(1);	// 休眠1毫秒,不然会输出不全
		for (j = k; j >= 0; j--) {
    
    
			if (r == a[j])  //与之前已存的随机数比较
				break;
		}
		if (j < 0) {
    
            //没有重复即保存到数组中
			a[k] = r;
			k++;
		}
	}
	qsort(a, 100, sizeof(int), cmp);	// 排序编号数组
	for (int i = 0; i < 100; i++) {
    
    
		m[i].id = a[i];		// 用排好序的编号赋给商场id
		m[i].q1 = rand();	// 四个季度营业额赋随机值
		m[i].q2 = rand();
		m[i].q3 = rand();
		m[i].q4 = rand();
		m[i].sum = m[i].q1 + m[i].q1 + m[i].q3 + m[i].q4;
		m[i].sum *= (double)rand() / RAND_MAX;
		// RAND_MAX是随机数最大值,rand()/RAND_MAX就是一个0-1的数,乘上总额可以变为浮点数,看起来比较真实(但没卵用,反正是随机数)
		printf("商场%-4d销售总额%8.2f万元\n", m[i].id, m[i].sum);
	}
	return 0;
}

14. Experiment 14: Comprehensive Application

1. Write a program, use a loop to generate the following data and store it in a disk file

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 \begin{matrix}2 & 3& 4&5 \\6& 7 & 8&9 \\10 & 11 & 12&13\\14&15&16&17\end{matrix} 261014371115481216591317

#include <stdio.h>
int main() {
    
    
	FILE *fp = fopen("14-1.txt", "w");	// 打开写入文件
	for (int i = 1; i < 17; i++) {
    
    	// 循环输入数字
		fprintf(fp, "%d\t", i + 1);	// 从2开始输出
		if (i % 4 == 0)		// 每4个数字换一行
			fprintf(fp, "\n");
	}
	fclose(fp);	// 关闭文件
	return 0;
}

2. There are n individuals who take the civil service examination of a certain profession, and their various results have been established in the format of text files and saved in the D:\2020 directory. The name of the data file is file_09.dat, and the format of the data creation is as follows: write a program, Find the average score of each person and output

考号 姓名 行政职业能力 公共基础知识 申论 专业知识 面试成绩
Without this dat file, write a function to create

void input_info() {
    
    	// 录入dat成绩文件
	FILE *fp = fopen("file_09.dat", "w");	// 打开一个写入文件
	long long id;	// 考号
	char name[20];	// 姓名
	double score[5];// 五科的成绩
	printf("输入录入人数:");
	int n;
	scanf("%d",&n);
	fprintf(fp,"考号 姓名 行政职业能力 公共基础知识 申论 专业知识 面试成绩\n");
	// 输入标头
	while (n--) {
    
    	// 循环输入姓名和成绩
		printf("请输入考号姓名:");
		scanf("%I64d%s", &id, name);
		fprintf(fp, "%I64d %s ", id, name);
		printf("请输入成绩:");
		for (int i = 0; i < 5; i++) {
    
    
			scanf("%lf", &score[i]);
			fprintf(fp, "%.2f ", score[i]);
		}
		fprintf(fp, "\n");
	}
	fclose(fp);
}

The established file is like this, you
insert image description here
can open it with Notepad
insert image description here

Query grades in the main function

#include <stdio.h>
#include <string.h>
#define MAX 100
typedef struct {
    
     // 存储公务员信息结构体
	long long id;
	char name[20];
	double score[5];
	double avg;
} gwy;
int main() {
    
    
//	input_info();	// 建立成绩dat文件
	gwy g[MAX];
	FILE *fp = fopen("file_09.dat", "r");
	while (1) {
    
    	// 读取第一行标头,将指针移到下一行
		char c = fgetc(fp);
		if (c == '\n') break;
	}
	int count = 0;	// 计数录入了多少个数据
	while (!feof(fp)) {
    
    
		double sum = 0;	// 总成绩和,为求平均成绩
		fscanf(fp, "%I64d %s", &g[count].id, g[count].name);	// 将数据存入结构体
		for (int i = 0; i < 5; i++) {
    
    
			fscanf(fp, "%lf", &g[count].score[i]);
			sum += g[count].score[i];
		}
		g[count].avg = sum/5;	// 平均成绩
		count++;
	}
	printf("%-16s%-10s%-6s\n","考号","姓名","平均成绩");	// 输出结果
	for (int i = 0; i < count - 1; i++) 
		printf("%-16I64d%-10s%-6.2f\n", g[i].id, g[i].name, g[i].avg);
	return 0;
}

3. Write a program to calculate the multiplication of two matrices

#include <stdio.h>
int main() {
    
    
	int r1, c1, r2, c2, i, j;	// r,c表示矩阵的行,列
	printf("输入第一个矩阵的行,列数:");
	scanf("%d%d", &r1, &c1);
	printf("输入第一个矩阵的元素:\n");
	int m1[r1][c1];
	for (i = 0; i < r1; i++)	// 循环录入第一个矩阵的所有元素
		for (j = 0; j < c1; j++)
			scanf("%d", &m1[i][j]);
	printf("输入第二个矩阵的行,列数:");
	scanf("%d%d", &r2, &c2);
	if (c1 != r2) {
    
    	// 判断矩阵是否能相乘
		printf("矩阵无法相乘\n");
		return -1;
	}
	printf("输入第二个矩阵的元素:\n");
	int m2[r2][c2];
	for (i = 0; i < r2; i++)
		for (j = 0; j < c2; j++)
			scanf("%d", &m2[i][j]);
	int re[r1][c2];	// 相乘结果矩阵
	for (i = 0; i < r1; i++)	// 矩阵相乘
		for (j = 0; j < c2; j++) {
    
    
			int sum = 0;	// 第一个矩阵的行分别乘第二个矩阵的列之和
			for (int k = 0; k < c1; k++)
				sum += m1[j][k] * m2[k][j];
			re[i][j] = sum;
		}
	printf("矩阵相乘的结果为:\n");
	for (i = 0; i < r1; i++) {
    
    
		for (j = 0; j < c2; j++)
			printf("%d\t", re[i][j]);
		printf("\n");
	}
}

4. A small software system for querying results

I also wrote a similar function for entering grade files

#include <stdio.h>
#include <string.h>
#define MAX 100
typedef struct {
    
     // 存储学生信息结构体
	char name[20];
	double score;
} Students;
void input_info() {
    
    
	FILE *fp = fopen("14-4.txt", "w");
	char name[20];
	double score;
	while (1) {
    
    	// 循环输入姓名和成绩
		printf("请输入姓名(输入*退出):");
		scanf("%s", name);
		if (strcmp(name, "*") == 0)	// 判断如果输入的字符串和*相等,退出循环,停止录入
			break;
		printf("请输入成绩:");
		scanf("%lf", &score);
		// 将数据写入文件
		fprintf(fp, "%s %.2f\n", name, score);
	}
	fclose(fp);
}
int main() {
    
    
//	input_info(); // 若无"学生姓名 成绩" 格式的文件,用input_info函数录入生成文件
	Students s[MAX];
	FILE *fp = fopen("14-4.txt", "r");
	int count = 0;	// 计数录入了多少个学生的数据
	while (!feof(fp)) {
    
    
		fscanf(fp, "%s %lf", s[count].name, &s[count].score);
		count++;
	}
	while (1) {
    
    	// 循环查询学生成绩
		char a[20];
		printf("请输入要查询的学生姓名:(输入*退出)\n");
		scanf("%s", a);
		if (strcmp(a, "*") == 0)
			break;
		int flag = 1, i;	// 遍历数组后若未找到姓名,则flag为1,输出未找到该学生
		for (i = 0; i < count; i++) {
    
    
			if (strcmp(s[i].name, a) == 0) {
    
    	// 遍历数组,寻找输入的学生姓名
				printf("%s的成绩为%.2f.\n", a, s[i].score);	// 输出成绩
				flag = 0;
				break;
			}
		}
		if (flag)
			printf("没有找到该学生\n");
	}
	return 0;
}

5. Write a program to replace part of the content in a text file

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    
    

	FILE *fp;
	char fileName[100], search[100], replace[100];
	char temp[1000], str[1000];

	printf("请输入文件名: ");  // 提示用户输入文件名(14-5.txt)
	scanf("%s", fileName);
	fp = fopen(fileName, "r");  // 打开文件

	if (fp == NULL) {
    
      // 如果文件打开失败,输出错误信息并退出程序
		printf("无法打开该文件\n");
		exit(0);
	}

	printf("文件内容:\n\n");
	while (fgets(temp, 1000, fp) != NULL) {
    
      // 逐行读取文件内容,并将其存储在temp字符串中
		printf("%s", temp);  // 输出当前行的内容
		strcat(str, temp);  // 将当前行的内容添加到str字符串中
	}
	fclose(fp);  // 关闭文件

replace:
	printf("\n\n请输入需要替换的单词或短语: ");
	scanf("%s", search);  // 获取需要替换的单词或短语
	char *pos = strstr(str, search);  // 在str字符串中查找search字符串,并返回第一次出现的位置
	if (pos == NULL) {
    
      // 如果未找到匹配项,输出错误信息并重新录入
		printf("未找到匹配项\n是否继续(y/n)?\n");
		char c;
		fflush(stdin);
		scanf("%c", &c);
		if (c == 'y' || c == 'Y') {
    
    	// 如果用户选择继续,则清空缓冲区并跳转至replace标签重新录入
			fflush(stdin);
			goto replace;
		} else
			exit(0);
	}

	printf("请输入替换成的单词或短语: ");
	scanf("%s", replace);  // 获取替换成的单词或短语
	int index = pos - str;  // 计算匹配项在str中的位置
	memmove(&str[index + strlen(replace)], &str[index + strlen(search)], strlen(str) - index - strlen(search) + 1);
	// 将匹配项后面的内容向后移动,为替换后的单词或短语腾出空间
	memcpy(&str[index], replace, strlen(replace));  // 在匹配项的位置处插入替换后的单词或短语

	fp = fopen(fileName, "w");
	fputs(str, fp);	// 将修改后的内容重新写入文件
	fclose(fp);

	printf("替换完成。文件内容为:\n\n");
	fp = fopen(fileName, "r");  // 打开替换后的文件,读取文件内容并输出
	while (fgets(temp, 1000, fp) != NULL) {
    
    
		printf("%s", temp);
	}
	fclose(fp);
	return 0;
}

epilogue

Please correct me if there are any mistakes and deficiencies, thank you for your support.

Guess you like

Origin blog.csdn.net/Naiqnilil/article/details/130318862