当前位置:网站首页>Programming travel function

Programming travel function

2022-04-23 14:00:00 Mi Mang

Hello! Hello, everyone ! This chapter will lead you to understand the knowledge of functions , This section will be divided into two parts to explain , I hope that's helpful


Preface

This chapter will introduce the functions and some precautions


One 、 Classification of functions

Functions are divided into : Library functions and custom functions
Let's talk about

1. Library function

The first is the library function , What is a library function ?
Library function is to encapsulate and store functions , A way for users to use , But library functions cannot be used directly , Add the file name where the library function is used to #include<> The library function can only be used inside

Two examples :
1.

#include<stdio.h>
#include<string.h>
int main()
{
    
	char arr1[] = "1234567";
	char arr2[] = "#######";
	char arr3[] = {
     0 };
	char arr4[] = "#####";
	strcpy(arr2, arr1);
	printf("%s\n", arr2);
	strcpy(arr3, arr1);
	printf("%s\n", arr3);
	strcpy(arr4, arr1);
	printf("%s\n", arr4);
	return 0;
}

 Insert picture description here
Let's analyze the program one by one ,strcpy Is a copy function , Put the destination of the copy in front , Copy the original code and place it in the back ( The order cannot be reversed ). because strcpy It's a library function , Header file to be indexed string To continue to use ,string The method of use can be found in MSDN Find , It's in English , If the little friends can't understand, they can next Continental Dictionary , Put the mouse over the words that can't be translated automatically , It's very easy to use . And then we go on , If you can see the above program, an error will be reported , This is because the array is out of memory when copying , To report a mistake , Abreast of the times vs Although the compiler reports an error, it can continue to compile , But there are problems with this procedure , We should reasonably arrange the memory space .
2.

#include<stdio.h>
#include<string.h>
int main()
{
    
	char arr1[] = "1234567";
	memset(arr1, '@', 4);
	printf("%s\n", arr1);
	char arr2[] = "1234567";
	memset(arr2+3, '@', 4);
	printf("%s\n", arr2);
	return 0;
}

 Insert picture description here This library function memset And strcpy Also, reference the header file string, and memset The function is to replace , This function can replace the content of your original code that you want to be replaced with the code you want , The usage of this function is , The leftmost bracket is the starting address of the content you want to change , In the middle is what you want to replace with , On the far right is the amount of content you want to replace , As shown in the figure above .
Summary : The library function can be used by referring to the header file when it is used , The role of each library function can be MSDN Find , Easy to use


Two 、 Custom function

This is more complicated , Let's take it step by step

#include<stdio.h>
int add(int a, int b)// Value transfer call : Transfer value 
{
    
	return a + b;// Variables in parentheses of functions are called formal parameters ( Formal parameters ), Only instantiated function parameters are called ( Allocate memory units ), The formal parameters are destroyed after the function is called 
}
void swep(int* a, int* b)// Address call : Address 
{
    
	int c = *a;// During the transmission of ginseng , A formal parameter is a temporary copy of an argument , He has his own memory space , Changing parameters does not change arguments 
	*a = *b;
	*b = c;
}
int main()
{
    
	int a = 0;
	int b = 0;
	scanf("%d %d", &a, &b);// The variables in parentheses after the function are arguments ( The actual parameter ), Arguments have definite values , It is convenient to transfer parameters 
	printf(" Value before exchange :%d %d\n", a, b);
	swep(&a, &b);
	printf(" Value after exchange :%d %d\n", a, b);
	int ret = add(a, b);
	printf("a And b And :%d\n", ret);
	return 0;
}

In the picture add And swep Is our custom function

Custom functions involve The ginseng , Define a function in the main function , The actual parameters in parentheses are the actual parameters , When implementing a user-defined function, the formal parameters obtained from the actual parameters are in the function brackets, that is, formal parameters . In procedure When going to the custom function , Custom functions can only open up space to run , Destroy immediately after the operation . When implementing custom functions , A formal parameter is a temporary copy of an argument , It has independent space , Changing the value of a formal parameter does not change the value of an argument , So if you want to change the arguments , To carry out Address call
Be careful : Functions can be called nested , But you can't nest definitions
The right way :

int add(int x,int y)
{
    
	return x+y;
	sub(a,b);
}
int main()
{
    
	return 0;
}

Wrong way :

int add(int x,int y)
{
    
	return x+y;
	int sub(int a,int b)
	{
    
		return x-y;
	}
}
int main()
{
    
	return 0;
}

The above error is nested definition , You guys must remember , Functions can be called nested , Cannot nest definitions


2. Chained access

int main()
{
    
	int len = strlen("abcdef");
	printf("%d\n",strlen("abcdef"));
	return 0;
}

Above picture ,strlen As printf The parameters of the function . Chained access links functions together like a chain
 Insert picture description here
This picture is also a chain access , So why is the result like this ? Let's see
The first line prints out :
12345
6
2
This is because the third in the first line printf The printed numbers are 12345 Add an enter key , Is the total 6 Elements , These six elements are the second in the first line printf Parameters of , So the second one printf The result of printing is 6 Add an enter key , And this result is the first printf Parameters to print ,6 The Enter key is two elements , Last printed out 2 That's where it came from
The second line prints :
12345 6 2
The same as the first line of print results , It's just There is a newline after the result in the first line Participate in printing as an element
And the second line is to Space Participate in printing as an element
The third line prints :
1234551
Because the third line %d There's nothing in the back , So , Third printf Print as many numbers as there are , No superfluous content , So in the second printf It seems that there is 5 Elements , first printf It seems that there is only one element


3、 ... and 、 Function declaration and definition

When a function is called, it must be declared first , We should pay great attention to this , Whether the function is called or not, it must be declared first , Then define , Finally, call
 Insert picture description here

 Insert picture description here

 Insert picture description here
The function declaration is in the header file , And then in 1.c File defines , stay 2.c The function can be called by importing the header file
The picture above is ,add Function in add.h File statement , stay add.c File defines , stay test.c The file references the header file and then calls.


Four 、 Recursion and iteration of functions

1、 recursive :

Recursion has two necessary requirements , Both of these requirements have recursion and may not compile correctly , But without these two requirements, the compilation must be incorrect

First of all : Recursion must have a limitation , When the constraints are met, the recursion will not continue
second : Every recursion , Will approach the constraints of recursion

These two conditions are essential

Enter a number , such as 123456, Output 1 2 3 4 5 6, We can print with a loop , But recursion is more convenient here

#include<stdio.h>
void print(unsigned int n)
{
    
	if (n > 9)
	{
    
		print(n / 10);
	}
	printf("%d ",n % 10);
}
int main()
{
    
	unsigned int num = 0;
	scanf("%d", &num);
	print(num);
	return 0;
}

 Insert picture description here

 Insert picture description here
 Insert picture description here
Recursion is the function call itself , The idea of this question is to first judge whether the input number is greater than 9, Greater than 9 It means double digits , Get into if sentence , Until the number recurses to less than 9 Then print back the numbers in turn


2、 iteration

A loop is an iteration , But iterations are not just loops
Find a Fibonacci number
Fibonacci sequence starts from the third number , The sum of the first two numbers is equal to the next number :
1,1,2,3,5,8,13,21,34,55…

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

The computer will find that it takes a long time to enter numbers recursively , This is very inconvenient , If the iterative method is used, will it be faster ? Let's try

#include<stdio.h>
int fib(int n)
{
    
	int a = 1;
	int b = 1;
	int c = 1;// When the input n Less than 3 when , The Fibonacci number is 1, take c Initialize to 1 You can print it out directly 1 Come on 
	while (n >= 3)
	{
    
		c = a + b;// The first number is a, The second number is b, Sum to get the third number c, then a and b The number represented moves backward as a whole 1, seek c, That is to say 
	// The second cycle , The second number is a, The third number is b, Sum to get the fourth number c
	// The third cycle , The third number is a, The fourth number is b, Sum to get the fifth number 
		// In turn, cycle , Until the second n A digital 
		a = b;
		b = c;
		n--;// Reduce one iteration after each iteration 
	}
	return c;
}
int main()
{
    
	int n = 0;
	scanf("%d", &n);
	int ret = fib(n);
	printf("%d\n", ret);
	return 0;
}

 Insert picture description here

You can see it , Iterations are performed when calculating large numbers , Although the answer is wrong , But fast and efficient , You can get results quickly , So Fibonacci number is more convenient to use iteration
Recursion and iteration should be carried out according to the actual situation

Okay , That's what this issue is about , Thank you for watching , I hope it will be helpful to all my friends , See you next time !

版权声明
本文为[Mi Mang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231357331092.html