C++ starts all over again: knowledge point speed pass

1. About scanf

1.1 Reading in numbers

The return value of scanf indicates the number of variables successfully input. When the input ends, scanf will not be able to read the data again and return 0

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

# define M 1000000;
// compute the max, min, average value of a given list
int main(){
    
    
	int x, min = M, max = -M;
	int n = 0;
	int sum = 0;
	printf("%d", min); 
	// scanf 读取结束后,则完成最后一次while循环。
	// windows的退出方法:回车-ctrl+z-回车 
	while(scanf("%d", &x) == 1){
    
    
		sum += x;
		n += 1;
		if (min > x){
    
    
			min = x;
		}
		if (max < x){
    
    
			max = x;
		}
	}
	printf("the max number in the list : %d\n", max);
	printf("the min number in the list : %d\n", min);
	printf("the average number in the list : %f\n", sum*1.0/n);
	return 0;
} 

1.2 Reading in a string

scanf(“%s”, s)

  • unnecessary&
  • The result of reading: a string without spaces, tabs, and carriage returns, stored in a character array s

1.3 Tips for outputting numbers: In the printf function, use variables to specify the number of decimal places

printf("%.*f", str_len, number);// str_len表示小数位数,number为浮点数变量

In the printf function, input a floating-point number with a certain number of digits

printf("%5d", n);  // (不超过五位时,)按照五位来打印,不足五位则补空格
printf("%05d", n); // (不超过五位时,)按照五位来打印,不足五位则补零
printf("%11.3f", f);// 打印数字占11位,保留小数点后3位,不足则补空格
printf("%011.3f", f);// 打印数字占11位,保留小数点后3位,不足则补零

2. Trivial Specifications

2.1 A solution to square overflow in the denominator position

Problem to be solved: Input multiple sets of n, m, and find the result of 1/n 2 +1/(n+1) 2 + ... +1/m 2 . When the input n and m are 0, the program ends.
Input example 1: 2 4
Input example 2: 65536 655360

In example 2, in the denominator part, if 1/(n*n) is used, the int storing the denominator will overflow; if the method of 1/n/n is used instead, floating point numbers can be used to avoid the possibility of overflow

# include <stdio.h>

int main(){
    
    
	int n, m, kase = 0;
	double sum = 0.0;

	while(scanf("%d %d", &n, &m) ){
    
    
		// time to end
		if (n==0 && m==0) break;
		// exchange the value if n is larger 
		if (n>m){
    
    
			int t = m;
			m = n;
			n = t;
		} 

		while(n <= m){
    
    
			// sum += 1.0/(n*n);
			sum += 1.0/n/n;  // 防止溢出
			n += 1;
		}
		
		kase += 1;
		printf("Case %d: %.5f\n", kase, sum);
		
	}
} 

2.2 floor() About the precision and rounding of floating-point numbers

In the process of writing functions, due to the calculation accuracy of floating-point numbers, it is similar to expressing 1.0 as 1.00001 or 0.9999998. In pure numerical operations, this kind of error is not a big problem. But when it comes to taking an integer, if you use the floor() function, the result of floor(1) may be judged as 0.

A common solution is to write in the format floor(a+0.5).
At first glance, it is to move the transition point of the piecewise function from the integer point to the position where the scale is 0.5. With a function similar to rounding, for example, a floating point number in the range of [0.5, 1.5) will be judged as 1 by floor().
In fact, this is a correction method. It does not solve the small error in the last digit of the floating-point number proposed above, but shifts the error from around 1.0, which has a large influence, to around 1.5, which has little influence. After all, the floating-point number error No matter how big it is, it can't be bigger than 0.5, right?

2.3 Use global variables with caution

Variables defined inside a function are called local variables, and vice versa are global variables

Global variables are easy to define and use, but they will not be released or reset at the end of the function.
This means that if two places call the same global variable sequentially and modify its value, even the same statement may have different results

# include <stdio.h>

int t = 0;
int g(){
    
     return ++t; }

int main(){
    
    
	int a, b;
	a = g();
	b = g();
	printf("%d %d", a, b);
	return 0;
}

The output is
1 2

3 Use files to complete input and output

3.1 Using file input and output - redirection (freopen)

# define LOCAL
# include <stdio.h>
# include <math.h>
# include <time.h>

# define M 1000000
// compute the max, min, average value of a given list
int main(){
    
    
	# ifdef LOCAL  // 若定义了LOCAL变量
	freopen("data.in", "r", stdin);
	freopen("data.out", "w", stdout);
	# endif  //编译结束
	int x, min = M, max = -M;
	int n = 0;
	int sum = 0; 
	// scanf 读取结束后,则完成最后一次while循环。
	// windows的退出方法:回车-ctrl+z-回车 
	while(scanf("%d", &x) == 1){
    
    
		sum += x;
		n += 1;
		if (min > x){
    
    
			min = x;
		}
		if (max < x){
    
    
			max = x;
		}
	}
	printf("the max number in the list : %d\n", max);
	printf("the min number in the list : %d\n", min);
	printf("the average number in the list : %f\n", sum*1.0/n);
	return 0;
} 

3.2 Using file input and output - fopen

# include <stdio.h>

# define M 1000000
// compute the max, min, average value of a given list
int main(){
    
    
	FILE *fin, *fout;
	// 声明变量 
 	fin = fopen("data.in", "rb");
 	fout= fopen("data.out", "wb");
	int x, min = M, max = -M;
	int n = 0;
	int sum = 0; 
	// fcanf三个参数:从哪读, 什么类型,赋给哪个参数 
	while(fscanf(fin, "%d", &x) == 1){
    
    
		sum += x;
		n += 1;
		if (min > x){
    
    
			min = x;
		}
		if (max < x){
    
    
			max = x;
		}
	}
	// 同样说明输出的位置 
	fprintf(fout, "the max number in the list : %d\n", max);
	fprintf(fout, "the min number in the list : %d\n", min);
	fprintf(fout, "the average number in the list : %f\n", sum*1.0/n);
	// 关闭文件 
	fclose(fin);
	fclose(fout);
	return 0;
} 

Under the condition of fopen, the flexibility is greater, and the file can be opened and read and written repeatedly.
When we want to modify the standard input and output again, we can modify fin, fout, and fclose as follows

# include <stdio.h>
# define M 1000000
// compute the max, min, average value of a given list
int main(){
    
    
	FILE *fin, *fout;
	// 声明变量,直接定位到标准输入输出 
// 	fin = fopen("data.in", "rb");
// 	fout= fopen("data.out", "wb");
	fin = stdin;
	fout = stdout; 
	int x, min = M, max = -M;
	int n = 0;
	int sum = 0; 
	// fcanf三个参数:从哪读, 什么类型,赋给哪个参数 
	while(fscanf(fin, "%d", &x) == 1){
    
    
		sum += x;
		n += 1;
		if (min > x){
    
    
			min = x;
		}
		if (max < x){
    
    
			max = x;
		}
	}
	// 同样说明输出的位置 
	fprintf(fout, "the max number in the list : %d\n", max);
	fprintf(fout, "the min number in the list : %d\n", min);
	fprintf(fout, "the average number in the list : %f\n", sum*1.0/n);
	// 无需关闭文件 
//	fclose(fin);
//	fclose(fout);
	return 0;
} 

4. Arrays and Strings

4.1 Regarding the definition position of larger arrays

Generally, only when the definition is outside the main function, the array can be opened very large

4.2 Copy some elements in the array to another array memcpy && zero the array memset

# include <stdio.h>
# include <string.h>
int main(){
    
    
	double a[10];
	double b[10];
	// 将数组 a 归零 
	memset(a, 0, sizeof(a));
	for (int i =0; i<10; ++i){
    
    
		a[i] = i;
	}
	
	for (int i =0; i<10; ++i){
    
    
		b[i] = i + 10;
	}
//	// 复制所有 a 中的元素到 b
//	memcpy(b, a, sizeof(a));
	// 复制 3个 a中的元素到 b 
	memcpy(b, a, sizeof(double)*3);
	for (int i=0; i<10; ++i){
    
    
		printf("%f ", b[i]);
	}
	return 0;
}

Regarding memset, the value for initializing the array is limited to 0 and -1.
This is because memset assigns a value byte by byte in memory. After the 4-byte int is assigned a value of 1 by memset, the obtained binary value is 00000001 00000001 00000001 00000001, which is not 1 when converted to decimal, and this value is in long It is different for other types of data such as long. Being able to initialize to 0 and -1 is purely coincidental
insert image description here

4.3 strlen, sprintf, strchr, strcpy, strcmp, strcat

  • The length of the string (character array) s mark may be very long, some of which actually store data, while the content of other positions is uncertain, and the function strlen() can obtain the actual length of the string s.
  • Similar to printf printing on the screen and fprintf printing on a file, sprintf can output content to a string
  • strchr(s, tmp[i]) can find a single character tmp[i] in a string s. If not found, the return value is NULL; if the character is found, the character and the following string are returned
  • char *strcpy(char *dest, const char *src): copy the string pointed to by src to dest
  • int strcmp(const char *str1, const char *str2): Compare the string pointed to by str1 with the string pointed to by str2 - if it is greater than 0, str1 is greater than str2 (not necessarily 1); if it is less than 0, it is less than; Equal to 0 is equal to
  • char *strcat(char *dest, const char *src): Append the string pointed to by src to the end of the string pointed to by dest, and the return value is a pointer to the final target string dest

4.4 getchar() reads characters one by one

When getchar() can read a character from standard input, it will return an int type.
This is because, when the file ends, a special mark EOF will be returned, because EOF is not a char, if a char is returned, the special EOF cannot be distinguished from ordinary characters.

In fact, getchar() is equivalent to replacing fin in fgetc(fin) with stdin

# include <stdio.h>
// replace the ' " ' with ' `` ' and ' !! ' in turn.
int main(){
    
    
	int c, q = 1;// getchar的返回值为int类型,故用int c记录
	while ((c = getchar()) != EOF ){
    
    
		if (c == '"'){
    
    
			// 因为双引号的出现,必然是前后相邻两个成对出现,这与括号的使用过程中可层层嵌套的用法不同。
			// 所以可以通过改变布尔值来交替输出两种符号
			printf("%s", q ? "``" : "!!");
			q = !q;
		}
		else printf("%c", c);
	}
	return 0;
}

insert image description here

4.5 isalpha、isdigit、sprint

isalpha(): Determine whether the character is a letter
isdigit(): Determine whether the character is a number
isprint(): Check whether the passed character is printable, printable such as 'k', space, etc., return true; non-printable For example \t, return false
toupper()
tolower()

The above functions are all declared in ctype.h

Guess you like

Origin blog.csdn.net/m0_53327618/article/details/127161716