C++ language foundation - function (detailed explanation)

Table of contents

what is the function

function definition

Main function example

 empty function

function call

grammatical format

Example: Calculate the nth power of x

recursion

The main point of recursion

recursive structure

condition

Scenarios for recursive use


what is the function

The full name of a function is a computer function , which can help you complete some specific programs. You can simply understand it as a pistol.

The function of the pistol: complete the function of shooting several bullets

The structure of the pistol: there are several fixed parts

Therefore, a pistol is a tool with a certain format that can perform some specific functions . This is the function

function definition

Main function example

int main(){
    cout << "Hello world!\n";
    return 0;
}

It follows that when a function is created, its definition must be written. All function definitions include the following components:

  • Name : Every function must have a name. In general, the same rules that apply to variable names also apply to function names.
  • Formal parameter list : The program module calling the function can send data to it. A formal parameter list is a list of variables that hold the values ​​passed to a function. If no value is passed to a function, its parameter list is empty.
  • Body : The body of a function is the set of statements that handle the task the function is performing. These statements are enclosed in a set of braces.
  • Return Type : A function can send a value back to the program module that called it. The return type is the data type of the value being sent back.

 grammatical format

返回值类型 函数名称 (参数列表)
{
	 函数体语句;
	 return 返回值;
}

 empty function

As mentioned earlier, functions can return a value . The main function in all the programs covered in the tutorial is declared to return an int value to the operating system. The "return 0;" statement causes the main function to return a value of 0 when it finishes executing

However, not all functions necessarily return a value . Some functions simply execute one or more statements and then return . In C++, such a function is called an empty function , for example

void shuchu()
{
    cout << "Hello world!\n";
}

 The name of this function is shuchu, and it is named in the same way as variables, and functions should be named in such a way that their function is revealed through the name . Because the function does not need to receive any information to perform its task, it has no parameter list in parentheses

The return type of this function is void . This means that the function does not return a value after it finishes executing , and returns to the part of the program that called it. Since there is no return value, no return statement is needed. When the statement in the function has finished executing and encounters the closing curly brace that terminates the function, the program will return automatically

function call

Function: use the defined function

Grammar format:

function name (parameter list)

Calling a function will result in the execution of the function. Function main is called automatically at program startup , but all other functions must be executed by function call statements . When a function is called, the program branches to the function and executes the statements in its body

Example: Calculate the nth power of x

#include<stdio.h>
#include<math.h>
double power(double x,int n)
{
  int m;
  m=pow(x,n);
  return m;
}
int main()
{
  double x,y;
  int n;
  scanf("%d%lf",&n,&x);
  y=power(x,n);
  printf("%.2f",y);
  return 0;
}

operation result:

In line 3, we define a function named power, whose actual function is to find the nth power of x . In the body of the function, a function in the math library —pow function is used , and its function is to find the power of x. nth power. At the end of the function, return a value of m

Like all C++ programs, the program starts executing from the main function, and other functions are only executed when they are called. In the above program, the function power is called by the following statement in the main function:

power(x,n);

recursion

Recursion refers to a method in which a program calls itself directly or indirectly . Through this form of execution, many operations that require some fixed steps can be performed. It can simplify a complex and huge problem by focusing on solving it. It is a good way to improve our coding efficiency ( recursion is easy to understand, but the memory is too high. It is recommended not to use recursion for large-scale exams (unless you have to use it, it is really impossible to do it) ))

The main point of recursion

  • Parameters and return values ​​of recursive functions
  • Termination condition
  • recursive logic design

For example (to find the factorial):

int factorial(int n){
    if(n==1)
        return n;
    else
        return n*factorial(n-1);
}
int main()
{
    int n;
    cout<<"请输入整数:"<<endl;
    scanf("%d",&n);
    cout<<"整数:"<<n<<"的阶乘为:"<<factorial(n)<<endl;
    cout<<"\n"<<endl;
    return 0;
}

This looks not difficult, isn't it just a multiplication? If you think about it carefully, it will take a long time for me to type it with a calculator.

But with recursion, this thing is easy to say:

This can be seen as multiplying two numbers : 100×(99×98×97×……×4×3×2×1)

The green product in the brackets is regarded as a number, so it's simple.

If you are still bored, the number in brackets can also be regarded as the multiplication of two numbers :

99×(98×97×……×4×3×2×1)

Didn't you find something? That's right, we treat a relatively complex formula as a whole, regardless of its specific value .

Everyone continue to think, if I still find it complicated in the brackets above? Can it continue to be divided into two numbers and multiplied? The answer is yes.

Then when can we get the answer directly by decomposing it?

Yes, if it is decomposed into 2×1, we can easily solve it.

Then 3×(2×1) is solved. In the same way:

4×(3×2×1) is solved. What about the same reason?

You should be able to think that 5× (4×3×2×1) has also been solved, and it can be solved slowly by continuing to expand.

100×(99×98×97×……×4×3×2×1)

recursive structure

    public void fun(参数) {
 
    if (终止条件) {
 
    return;
 
    }
 
    fun(参数);
 
    (其他判断条件或语句);
 
    }

In the above code, when entering the function for the first time, first judge whether the termination condition is met , if it is met , the function will be terminated directly , if it is not met, enter the next statement , and call itself to re-enter the next layer of self function The layer will not continue to execute the statement downwards, and the outer layer is stuck at the fun (parameter)), the operation process of calling itself into its own function is the process of "passing" . Assume that after entering the next layer, the termination condition is met and the result is returned. At this time, the function of the outermost layer is returned after entering its own function execution, and the result is obtained at the recursive call of the outermost layer function, (that is, the result return value is obtained after the execution of the inner layer function is completed. ), this process is the process of "returning". At this time, the outermost function can continue to execute the next statement until the function is completed.

condition

Recursion must meet two conditions

  • One is the boundary, that is, the termination condition.

  • Second, you need to call yourself.

Scenarios for recursive use

1. A large problem can be split into multiple sub-problems .

2. The original problem and the split sub-problems have exactly the same solution ideas except for the different data scales .

3. There is a recursive termination condition .

Recursion is less obvious to use in linear data structures, and iteration can basically solve problems very easily.

Recursion is very important in nonlinear structures, such as binary trees, backtracking, typical tree problems - Jiugongge letter combinations

Common errors when using functions

1 Redefine variables             

Error:redefinition of 'a'

2 missing semicolon

Error:expected ';' after expression 

3 wrong number of array dimensions

Error:array type 'int [101]' is not assignable

4 About if and else

Error:expected expression

Warning: equality comparison result unused [-Wunused-comparison]

There can be no semicolons in the if judgment!

5 about if and else

This is to write the equal sign as an assignment sign

 Warning: using the result of an assignment as a condition without parentheses [-Wparentheses]

This is a special pit! ! !

6 Parentheses matching error

Error: expected ']'

Error: expected ']'

Error: extraneous closing brace ('}')

7 Input error about character string(*)

Error:  invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'char *')
        cin>>c+1;
        ~~~^ ~~~

Warning: operator '>>' has lower precedence than '+'; '+' will be evaluated first [-Wshift-op-parentheses]
        cin>>c+1;
           ~~~^~

Note: candidate function template not viable: no known conversion from 'std::istream' (aka 'basic_istream<char>') to 'std::byte' for 1st argument
  operator>> (byte  __lhs, _Integer __shift) noexcept
  ^

8 Wrong function/variable name

Error: use of undeclared identifier 'mam'; did you mean 'max'?

It is easy for young people to learn but difficult to achieve, and an inch of time is not to be taken lightly. Unaware of the dream of spring grass in the pond, the sound of autumn leaves in front of the steps 

Guess you like

Origin blog.csdn.net/qiuweichen1215/article/details/129857014