函数是一种子程序,最重要的意义在于抽象数据处理的过程。
在C语言中,函数的基本语法罗列如下。
type function_name(argument_list)
{
// code
}
学习一项知识点的最好办法,就是动手实践,下面,我们集中展现这一过程。
/*
function.c
Use the function to solve the problem
BeginnerC
*/
#include <stdio.h>
#define C 299792458
/*
calc
Calc the E = mc^2
Argument
m
The mass
Return Value
The energy
*/
double calc(double m)
{
return m * C * C;
}
int main()
{
double m = 0.0;
scanf("%lf", &m);
printf("E = %f\n", calc(m));
return 0;
}
在这一案例之中,我们将 E=mc2E=mc2 集中封装为一个函数,如您所见,函数的返回值被定义为 double ,参数也是 double 类型。
这是一个简单的函数,事实上,我们还可以使用函数去解决更加复杂的问题。
/*
function_second.c
Use the function to solve the problem
BeginnerC
*/
#include <stdio.h>
/*
Pow
Calc the a^b
Argument
a
original number
b
power number
Return Value
The result is a^b
*/
double Pow(double a, double b)
{
if (b <= 1)
{
return a;
}
return a * Pow(a, b - 1);
}
int main()
{
printf("%lf\n", Pow(2, 3));
return 0;
}
在这个程序之中,我们计算,并将其抽象为一个函数,值得注意的是,这个 Pow,用自己调用自己。
这种情况被称为递归,递归的本质就是:改变输入的数据,用同样的逻辑处理数据。