当前位置:网站首页>C language learning day_ 05
C language learning day_ 05
2022-06-27 09:57:00 【Bad bad -5】
List of articles
- Learning reference B Stand on the video of teacher Hao bin , The source code in the article can be contacted by private letter if necessary .
function
- It's a tool , Not designed for a problem , It is designed for a large number of problems of the same type
- The number of functions processed is different , But the operation of data is the same
- What is a function
- logically : A separate block of code that performs a specific function
- Physically : Be able to process the received data , And return the value
- You can also not accept data , No return value
example :
/* Example of function */
# include <stdio.h>
int f(void) //int Represents the return value type of the function ,void Indicates that the function cannot receive data
{
return 5; // Returns... To the calling function 5
}
void g(void) // Before the function name void Indicates that the function has no return value
{
return 3; //error, no return value , Using this statement will report an error
}
int main(void)
{
int j = 10;
j = f(); // No value is written in parentheses
printf("%d\n", j); // Output f The return value of the function 5
j = g(); //error, because g Function has no return value , So you can't assign values
return 0;
}
Why function is needed
- The operation on the data is the same , You need to operate on multiple data , You need to use functions to reduce the amount of code
- You can avoid writing a lot of repetitive code
- It is conducive to the modularization of the program
example : existing a-f common 6 A variable , Each variable has a value , It is required to compare a、b,c、d,e、f Size between , And output a larger number .
/* existing a-f common 6 A variable , Each variable has a value , It is required to compare a、b,c、d,e、f Size between , And output a larger number */
# include <stdio.h>
int main(void)
{
int a, b, c, d, e, f;
a = 1, b = 2, c = 4, d = -3, e = 5, f = 10; // Comma expression
/* Because the whole is not assigned to the variable , So it doesn't affect , You can also use semicolons to separate a = 1; b = 2; ... */
if (a > b)
printf("max = %d\n", a);
else
printf("max = %d\n", b);
if (c > d)
printf("max = %d\n", c);
else
printf("max = %d\n", d);
if (e > f)
printf("max = %d\n", e);
else
printf("max = %d\n", f);
return 0;
}
/* Running results */
max = 2
max = 4
max = 10
Press any key to continue
- Statements with the same function , Wrote many times , You can use functions , To call , Save code
Method 1 :
/* existing a-f common 6 A variable , Each variable has a value , It is required to compare a、b,c、d,e、f Size between , And output a larger number */
# include <stdio.h>
void max(int i, int j) // Defined function
{
if (i > j)
printf("max = %d\n", i);
else
printf("max = %d\n", j);
}
int main(void)
{
int a, b, c, d, e, f;
a = 1, b = 2, c = 4, d = -3, e = 5, f = 10;
max(a, b); // Call function
max(c, d);
max(e, f);
return 0;
}
voidIndicates that the function has no return value ,maxIs the name of the function ,i、jIt's a formal parameter , Formal parameter- Program execution , from
mainStart execution , Execute tomax(a, b);after , Think this is a call to a function , Start checking if..., is definedmaxFunction of
- Call the
maxfunction , And then a Assign a value to i,b Assign a value to j, Execute function- After the function is executed , The address space allocated to the formal parameter will be freed
/* Running results */
max = 2
max = 4
max = 10
Press any key to continue
Method 2 :
/* existing a-f common 6 A variable , Each variable has a value , It is required to compare a、b,c、d,e、f Size between , And output a larger number */
# include <stdio.h>
int max(int i, int j) // Defined function
{
if (i > j)
return i; // take i Return to the calling function
else
return j;
}
int main(void)
{
int a, b, c, d, e, f;
a = 1, b = 2, c = 4, d = -3, e = 5, f = 10;
printf("max = %d\n", max(a, b)); // The main function will i Output
printf("max = %d\n", max(c, d));
printf("max = %d\n", max(e, f));
return 0;
}
- The output is the same as above
- The difference is that the called function in the first program directly outputs the result , And in the second program , The called function returns the value to the calling function , Processed by the main function
How to define a function
- The essence of function definition is to describe in detail the specific method why a function can realize a specific function
return expression ;The meaning of- Terminate called function , Returns the value of the expression to the calling function
- If the expression is empty , Then only terminate the function , No value returned
breakUsed to terminate loops andswitch
example :return and break The difference between
/*return and break The difference between */
# include <stdio.h>
void f(void)
{
int i;
for (i = 0; i < 5; ++i)
{
printf("Bad!\n");
break; // What ends is for loop
}
return; // What ends is f function
printf("Boy!\n"); // No output
}
int main(void)
{
f();
return 0;
}
/* Running results */
Bad!
Press any key to continue
- The type of the return value of the function is also the type of the function
- If the return value type before the function name is the same as that in the function execution body
return expressionDifferent types , Then the type of the final function return value is the return value type before the function name
- If the return value type before the function name is the same as that in the function execution body
- Format
Type of function return value Function name ( Formal parameter requirements of function )
{
The body of the function
}
example : Type of function return value
/* Type of function return value */
# include <stdio.h>
int f()
{
return 3.5; // Because the return type of the function is int, So the final returned value is 3
}
int main(void)
{
double x = 5.5;
x = f(); // Call function , The value type is subject to the type before the function name
printf("%lf\n", x);
return 0;
}
- function f The return value in is floating point , The type before the function name is an integer
- If the function value type is
returnThe type returned shall prevail , Is returned 3.5. If the function value type is the type before the function name , Then the function value is 3
/* Running results */
3.000000
Press any key to continue
Classification of functions
- Parametric and nonparametric functions
- There are return values and no return values
- Library functions and custom functions
- Value transfer function and address transfer function
- Ordinary functions and main functions (main function )
- A program must have and only have one main function
- The main function can call ordinary functions , Ordinary functions cannot call the main function
- Ordinary functions can call each other
- The main function is the entry and exit of the program
Program examples
example : Judge whether a number is a prime number
/* Judge whether a number is a prime number */
# include <stdio.h>
int main(void)
{
int val;
int i;
printf(" Please input the number to be judged :");
scanf("%d", &val);
for (i = 2; i < val; ++i)
{
if (val % i == 0)
break; // End for loop
}
if (i == val)
printf("%d Prime number !\n", val);
else
printf("%d Not primes !\n", val);
return 0;
}
/* Running results */
Please input the number to be judged :13
13 Prime number !
---------------------
Please input the number to be judged :9
9 Not primes !
Press any key to continue
Defined function
/* Judge whether a number is a prime number 【 Defined function 】*/
# include <stdio.h>
bool IsPrime(int val) //bool Type data returns true or false
{
int i;
for (i = 2; i < val; ++i)
{
if (val % i == 0)
break;
}
if (i == val)
return true; //return Will terminate the function
else
return false;
}
int main(void)
{
int m;
printf(" Please input the number to be judged :");
scanf("%d", &m);
if (IsPrime(m)) // Judge whether the return value of the called function is true
printf("%d Prime number !\n", m);
else
printf("%d Not primes !\n", m);
return 0;
}
- The output is the same as above
Function declaration
- The definition function should be written before calling the function , If it is written after calling the function , You need to write a function declaration
- Function pre declaration
- Tell compiler , The coming letters represent a function
- Tell compiler , Several letters represent the formal parameters and return values of the function
- A function declaration is a statement , You must use a semicolon
- The library function is declared through `# inculde < The file name of the file where the library function is located .h> To achieve
example :
/* Function declaration */
# include <stdio.h>
void f(void); // Function declaration
int main(void)
{
f();
return 0;
}
void f(void)
{
printf("Bad Boy!\n");
}
/* Running results */
Bad Boy!
Press any key to continue
Formal parameters and actual parameters
- The position and number of formal parameters and arguments must correspond to each other , Types must also be compatible
example :
/* Formal parameters and actual parameters */
# include <stdio.h>
void f(int i, int j) // Shape parameter
{
printf("%d %d\n", i, j);
}
int main(void)
{
f(3, 5); // Actual parameters
return 0;
}
/* Running results */
3 5
Press any key to continue
Reasonably design functions to solve practical problems
example : The user enters a number , Output 0 All prime numbers between this number
/* The user enters a number , Output 0 All prime numbers between this number */
# include <stdio.h>
int main(void)
{
int i, j;
int val;
printf(" Please enter a number :");
scanf("%d", &val);
printf(" Prime numbers have :");
for (i = 2; i <= val; ++i)
{
for (j = 2; j < i; ++j)
{
if (0 == i % j)
break;
}
if (i == j)
printf("%d ", i);
}
printf("\n");
return 0;
}
/* Running results */
Please enter a number :50
Prime numbers have :2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Press any key to continue
- The reusability of the above code is not high , Not easy to understand , There are limitations
Method 2 : Defined function
/* Defined function , Outputs the prime number between the specified numbers */
# include <stdio.h>
bool IsPrime(int m) // The definition function only determines whether a number is a prime number
{
int i;
for (i = 2; i < m; ++i)
{
if (0 == m % i)
break;
}
if (i == m)
return true;
else
return false;
}
int main(void)
{
int i, val;
printf(" Please enter a number :");
scanf("%d", &val);
printf(" Prime numbers have :");
for (i = 2; i <= val; ++i)
{
if (IsPrime(i))
printf("%d ", i);
}
printf("\n");
return 0;
}
Optimize :
/* Defined function , Outputs the prime number between the specified numbers */
# include <stdio.h>
bool IsPrime(int m) // The definition function only determines whether a number is a prime number , Yes, go back to true, Otherwise return to false
{
int i;
for (i = 2; i < m; ++i)
{
if (0 == m % i)
break;
}
if (i == m)
return true;
else
return false;
}
void TraverseVal(int n) // Define the function to 1-n All prime outputs between
{
int i;
printf(" Prime numbers have :");
for (i = 2; i <= n; ++i)
{
if (IsPrime(i))
printf("%d ", i);
}
printf("\n");
}
int main(void)
{
int val;
printf(" Please enter a number :");
scanf("%d", &val);
TraverseVal(val); // Call function
return 0;
}
- The function is C The basic unit of language , Class is Java,C#,C++ The basic unit of
Common system functions
double sqrt(double x); // seek x The square root of
int abs(int x); // Seek shaping x The absolute value of
double fabs(double x); // Finding floating point numbers x The absolute value of
Scope and storage of variables
- Scope
- Global variables
- local variable
- A variable or function parameter defined inside a function
- Can only be used within this function
- How variables are stored
- Static variables
- Automatic variable
- Register variables
example :
/* Scope of variable */
# include <stdio.h>
void g()
{
printf("k = %d\n", k); //error, because k Variables are defined after the function
}
k = 3; // Global variables , After that, all functions can call
void f(int i) // local variable , Only this function can call
{
int j = 5; // local variable
int i = 3; //error, Because the variable name in the formal parameter conflicts with the variable name in the function
}
- Inside a function , If the defined local variable name is the same as the global variable name , Local variables mask global variables
【 Article source code reference GitHub】
All of the above are original , If unknown or wrong , Please point out .
边栏推荐
- 感应电机直接转矩控制系统的设计与仿真(运动控制matlab/simulink)
- Prometheus alarm process and related time parameter description
- Use of bufferedwriter and BufferedReader
- torch. utils. data. Randomsampler and torch utils. data. Differences between sequentialsampler
- 小白也能看懂的网络基础 03 | OSI 模型是如何工作的(经典强推)
- Record in detail the implementation of yolact instance segmentation ncnn
- 12个网络工程师必备工具
- JS 客户端存储
- R language plot visualization: plot to visualize the two-dimensional histogram contour map, add numerical labels on the contour lines, customize the label font color, and set the mouse hover display e
- 文件名设置导致writelines写入报错:OSError: [Errno 22] Invalid argument
猜你喜欢
随机推荐
The R language uses the preprocess function of the caret package for data preprocessing: Center all data columns (subtract the average value from each data column), and set the method parameter to cen
Freemarker
Explain the imaging principle of various optical instruments in detail
leetcode:968. Monitor the binary tree [tree DP, maintain the three states of each node's subtree, it is very difficult to think of the right as a learning, analogous to the house raiding 3]
js中的数组对象
【SO官方采访】为何使用Rust的开发者如此深爱它
使用Aspose.cells将Excel转成PDF
技术与业务同等重要,偏向任何一方都是错误
谷歌浏览器 chropath插件
Reorganize common shell scripts for operation and maintenance frontline work
torch. utils. data. Randomsampler and torch utils. data. Differences between sequentialsampler
On anchors in object detection
JS 文件上传下载
导师邀请你继续跟他读博,你会不会立马答应?
Understand neural network structure and optimization methods
.NET 中的引用程序集
torchvision.models._utils.IntermediateLayerGetter使用教程
unity--newtonsoft.json解析
R语言plotly可视化:可视化多个数据集归一化直方图(historgram)并在直方图中添加密度曲线kde、设置不同的直方图使用不同的分箱大小(bin size)、在直方图的底部边缘添加边缘轴须图
Quelques exercices sur les arbres binaires








