[Following C++] C++ functions (Study6)


 =============================== [Description] ===================== ====================================
  Hello everyone, this column is mainly to learn C++ content, I learned this blogger myself The [C++ 21-day Cultivation Plan] of the host [ AI Bacteria ] is very clear and suitable for beginners. I hope to give this blogger more attention, favorites, and likes.
  Mainly aiming at the content learned, organize it through your own understanding. I hope that everyone will actively communicate, discuss and give more opinions. I will also update you later, and some other knowledge. If there is any infringement, please contact to delete! Let's protect the rights of network knowledge together!
 ==================================================== ========================================

1. Function

1.1 Understanding functions

  When it comes to functions, you may have learned mathematics in middle school and college. The functions in C++ and the functions in mathematics have the same features, both represent a mapping relationship (logical relationship in C++), and also have corresponding input and output.
  In C++, a function is a group of statements (or block of statements) that together perform a task. main()Each program has at least one function, which is a function in the previous program , called the main function, and the program starts to execute from the main function.
  In normal study, or in small programs, we can main()implement it in the main function. However, when it comes to large projects, main()functions cannot keep the program readable and logical, so functions must be used. Functions divide and organize the execution logic of a program. Functions can be used to divide a complex and lengthy program into program blocks that are called sequentially.

1.2 Function definition and declaration

(1) Function definition
  In C++, the basic form of function definition is as follows:

return_type function_name(parameter list)
{
    
    
	函数主体;
}

  return_type : return type, indicating the data type of the return value of the function, the function generally has a return value, but it can also only perform some operations without returning any value, and the return type is void.
  function_name : This is the name of the function, customized according to the rules of definition and readability.
  parameter list : parameter list, the parameter is the placeholder, when calling the function, pass a certain value to the parameter, the value is called the actual parameter (actual parameter). The parameter list includes function parameter type, order and quantity. Among them, the parameters are optional, and may or may not contain parameters.
  Function body : A function body structure, a statement or statement block that performs some operations.
Understand the function through an example to calculate the area of ​​a circle.

#include <iostream>
using namespace std;

const double PI = 3.14;
double Circle_Area(double r) {
    
    

	return PI * r*r;

}

int main() {
    
    
	cout << "请输入圆的半径:" << endl;
	double radius = 0;
	cin >> radius;
	cout << "圆的面积为:" << Circle_Area(radius) << endl;
	return 0;

}

insert image description here
(1) Function declaration
  A function declaration tells the compiler the name of the function and how it should be called . The function call is of the form:

return_type function_nama(parameter list);

  A function definition is similar to a function declaration, the difference is that a semicolon is added at the end of the statement. We can declare the function as:

double Circle_Area(double r); 

  Of course, we can also just keep the parameter type without writing the parameter name:

double Circle_Area(double ); 

  When programming, I personally think it is better to write the parameter name, which is a programming habit.
  
  There are two situations for function declaration:
  1) Those who understand C++ should know that it can be executed normally without declaring the function in the above case. This is one of those cases where the function declaration can be omitted if the function definition comes beforemain() the function . If the function declaration comes after , then the function declaration is required. For example:main()

#include <iostream>
using namespace std;
double Circle_Area(double r);

const double PI = 3.14;


int main() {
    
    
	cout << "请输入圆的半径:" << endl;
	double radius = 0;
	cin >> radius;
	cout << "圆的面积为:" << Circle_Area(radius) << endl;
	return 0;
}
//函数定义在main()之后
double Circle_Area(double r) {
    
    

	return PI * r*r;
}

  2) If a function is defined in one source file and another file needs to be called, the function must be declared.

1.3 Function calls

  When C++ defines a function, the main function of the function is to solve a certain problem or complete a certain task, such as calculating area, perimeter, and so on. Then complete the task by calling a function. When calling a function, pass the required parameters , and if the function returns a value, you can store the value returned by the function. Also take the calculation of the area of ​​a circle as an example:

#include <iostream>
using namespace std;
double Circle_Area(double r);

const double PI = 3.14;

int main() {
    
    
	cout << "请输入圆的半径:" << endl;
	double radius = 0;
	cin >> radius;
	cout << "圆的面积为:" << Circle_Area(radius) << endl;
	return 0;
}
//函数定义在main()之后
double Circle_Area(double r) {
    
    
	S=PI * r*r
	return S;//函数返回值,可以存储该值
}

insert image description here

1.4 Formal Participation and Actual Parameters

  Formal parameter : If the function uses parameters, then a variable that accepts the value of the parameter must be declared, that is, the radius in the above case r, and this parameter is called a formal parameter. Formal parameters are similar to local parameters, created when entering a function (calling a function), and destroyed when exiting a function.
  Actual parameters : When calling a function, we need to use actual parameters, and the compiler will automatically pass the actual parameters to the formal parameters, and then execute the function body. In the above case, the actual parameter value is the radius input by the user, and then the compiler passes the radius value to the formal parameter to execute the function.

2. Function default parameters

  In the previous case, pi is fixed, so it is defined as an immutable constant. If we want to increase the accuracy of the circle area, then two decimal places are not enough. Here you can use default parameters to solve this problem and Circle_Area()add default parameters to the function PI. For example:

double Circle_Area(double r, double Pi=3.14);

  Since PIit is a default parameter, the user can choose or not to choose when calling the function. If not, the default value is 3.14. If I want to improve the calculation accuracy, I can re-specify the value when calling the function PI, for example:

//调用函数
Circle_Area(radius, 3.1415);

  Therefore, the previous case can be updated:

#include<iostream>
using namespace std;

double Circle_Area(double r, double Pi = 3.14); //函数声明 
int main()
{
    
    
	cout << "请输入圆形的半径radius:";
	double radius = 0, area = 0; //初始化半径 、面积 
	cin >> radius;     //输入半径 
	area = Circle_Area(radius);  //将函数的返回值给area 
	cout << "使用默认值Pi,该圆的面积是:" << area << endl;

	area = Circle_Area(radius, 3.1416);
	cout << "指定Pi=3.1416后,该圆的面积是:" << area << endl;
	return 0;
}

double Circle_Area(double r, double Pi)
{
    
    
	double S = Pi * r*r;  //就算圆的面积 
	return S;  //返回面积S 
}

insert image description here

3. Recursive function

  The Fibonacci sequence should be familiar, this is a typical case of recursive functions. In layman's terms, the function adjusts itself, and we call it a recursive function . A recursive function must have an exit condition, that is, when a certain condition is met, the function exits. Then the Fibonacci function is: Fn=Fn-1+Fn-2, F1=F2=1. We complete the Fibonacci sequence in C++.

//斐波那契数列
int Fibonacci(int n) {
    
    
	if (n==1||n==2)
	{
    
    
		return 1;

	}
	else
	{
    
    
		return Fibonacci(n - 1) + Fibonacci(n - 2);
	}
}

int main() {
    
    
	int n = 0;
	cout << "请输入Fibonacci要输出的第几个数:" << endl;
	cin >> n;
	cout <<"Fibonacci第 "<<n<<" 个数为:" <<Fibonacci(n);
	return 0;
}

insert image description here

4. Handle different types of data

  In the above cases, most of the calling functions use some integer and floating-point numbers. In fact, data such as arrays can be passed when the function is passed.

4.1 The parameter is an array

  Let's define a function. The first parameter of this function is an array, and the second parameter is the length of the array to ensure that the array does not overflow.

void Arr(int NumArr[],int length);

  Display an array of integers and an array of characters by calling:

#include<iostream>
using namespace std;

void ShowArr(int NumArr[], int length)
{
    
    
	for (int i = 0; i < length; i++)
		cout << NumArr[i] << " ";
}

void ShowArr(char CharArr[], int length)
{
    
    
	for (int i = 0; i < length; i++)
		cout << CharArr[i] << " ";
}

int main()
{
    
    
	int numarr[5] = {
    
     1,2,3,4,5 };
	ShowArr(numarr, 5);
	cout << endl;
	char chararr[6] = {
    
     'w','o','r','l','d','\0' };
	ShowArr(chararr, 6);
	return 0;
}

insert image description here

4.2 Function overloading

  Did you find that in the above case, the same function is defined. Among them, the function name and return type are the same, but the parameters are different. Such functions are called function overloading .
  In a real program, overloading a function is useful if you need to call a function with the same name and return type with different parameters.
  We can get acquainted by calculating the area of ​​a circle and the area of ​​a cylinder. The area of ​​a circle requires only the radius, while the area of ​​a cylinder also requires parameters 高h. The return data types of these two functions are the same, and both are areas. Then we can define a function with the same name Area(), where the first function has only parameters radius, and the other function includes radius and height.

#include<iostream>
using namespace std;

const double PI = 3.14;
double Area(double r);
double Area(double r, double h);

double Area(double r) {
    
    
	double S = PI * r*r;
	return S;

}

double Area(double r, double h) {
    
    
	double S = 2 * PI*r*h + PI * r*r;
	return S;
}

int main() {
    
    
	int r = 0, h = 0;
	cout << "请输入圆的半径和圆柱的高:";
	cin >> r >> h;
	cout << "圆的面积为:" << Area(r)<<endl;
	cout << "圆柱的面积为:" << Area(r, h) << endl;
	return 0;

}

insert image description here

4.3 Pass parameters by reference

  According to the needs of the program, we want the parameters modified inside the function to be available outside the function, so the type of the formal parameter can be declared as 引用&.
  &, the compiler knows that this parameter will not be copied to the function, but a reference to the actual parameter will be passed to the parameter.

#include<iostream>
using namespace std;

const double Pi=3.14;
void Area(double r, double& result) //result为将要返回的值的引用
{
    
    
	result=Pi*r*r;
}

int main()
{
    
    
	cout<<"输入半径radius:";
	double radius=0;
	cin>>radius;
	double GetResult=0;//定义
	Area(radius,GetResult);
	cout<<"圆的面积是:"<<GetResult<<endl;
	return 0;
}

  Therefore, the return type of this function is void, because the function no longer provides the calculated area by return value, but provides it by reference as an output parameter.

5. Summary

  Finally, to make a long story short, everyone should practice it after reading it. Remember not to be hot for three minutes, fish for three days, and post on the net for two days. You can also try to write a blog by yourself to record your usual learning progress. You can communicate and discuss with many scholars on the Internet, and I will update it in time to supervise your own learning progress. The blogger [ AI Bacteria ] mentioned at the beginning, I have personally followed and subscribed to the relevant column (helpful to me), I hope everyone thinks it is good, you can like, follow, and bookmark

Guess you like

Origin blog.csdn.net/qq_41225961/article/details/124760767#comments_27333934