当前位置:网站首页>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 .
边栏推荐
- JS array splicing "suggested collection"
- 借助原子变量,使用CAS完成并发操作
- 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
- TDengine 邀请函:做用技术改变世界的超级英雄,成为 TD Hero
- [registration] infrastructure design: from architecture hot issues to industry changes | tf63
- Google browser chropath plug-in
- 详细记录YOLACT实例分割ncnn实现
- 一次线上移动端报表网络连接失败问题定位与解决
- Vector:: data() pointer usage details
- torch. utils. data. Randomsampler and torch utils. data. Differences between sequentialsampler
猜你喜欢

Video file too large? Use ffmpeg to compress it losslessly

When does the mobile phone video roll off?

Privacy computing fat offline prediction

There is no doubt that this is an absolutely elaborate project

别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!

细说物体检测中的Anchors

This application failed to start because it could not find or load the QT platform plugin
测试同学怎么参与codereview

ucore lab3

Apache POI的读写
随机推荐
[200 opencv routines] 211 Draw vertical rectangle
ucore lab3
leetcode:522. 最长特殊序列 II【贪心 + 子序列判断】
R语言plotly可视化:plotly可视化二维直方图等高线图、在等高线上添加数值标签、自定义标签字体色彩、设置鼠标悬浮显示效果(Styled 2D Histogram Contour)
如何获取GC(垃圾回收器)的STW(暂停)时间?
[200 opencv routines] 212 Draw a slanted rectangle
为智能设备提供更强安全保护 科学家研发两种新方法
Quelques exercices sur les arbres binaires
Privacy computing fat offline prediction
Prometheus alarm process and related time parameter description
BufferedWriter 和 BufferedReader 的使用
邮件系统(基于SMTP协议和POP3协议-C语言实现)
Brother sucks 590000 fans with his unique "quantum speed reading" skill: look at the street view for 0.1 seconds, and "snap" can be accurately found on the world map
巴基斯坦安全部队开展反恐行动 打死7名恐怖分子
12个网络工程师必备工具
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]
Tdengine invitation: be a superhero who uses technology to change the world and become TD hero
Explain the imaging principle of various optical instruments in detail
我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
不容置疑,这是一个绝对精心制作的项目