C语言函数入门

85 阅读1分钟

函数是一种子程序,最重要的意义在于抽象数据处理的过程

在这里插入图片描述

在C语言中,函数的基本语法罗列如下。

type function_name(argument_list)
{
	// code
}

学习一项知识点的最好办法,就是动手实践,下面,我们集中展现这一过程。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gmjaTdRK-1683023041045)(https://foruda.gitee.com/images/1677754826510390025/18644f71_871414.png "1673226069806.png")]

/*
    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 类型。

这是一个简单的函数,事实上,我们还可以使用函数去解决更加复杂的问题。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EaF1vUq9-1683023041045)(https://foruda.gitee.com/images/1677754835140878691/bffb5802_871414.png "1673226468176.png")]

/*
    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;
}

在这个程序之中,我们计算ab a^b,并将其抽象为一个函数,值得注意的是,这个 Pow,用自己调用自己。

这种情况被称为递归,递归的本质就是:改变输入的数据,用同样的逻辑处理数据