C 笔记九 求幂函数

编写函数,计算整数 m 的 n 次幂。

/* power.c */
#include 

/* funtion prototype */
int power(int base, int time);

int main() {
    int i;
    
    for (i = 1; i <= 10; ++i) {
        printf("2^(%d)\t=%6d\n", i, power(2, i));
    }

    return 0;
}

int power(int base, int time) {
    int res = 1;
    
    while (time) {
        res *= base;
        --time;
    }

    return res;
}

这里定义了一个函数用于求幂。函数定义可以以任意次序出现在一个或多个源文件中,但同一个函数不能分割存放在多个源文件中。函数定义的一般形式为:

return_type funcName(arguement-list) {
    statement;
}

power 函数的第一行语句声明了参数类型、函数名称和返回的结果类型:

int power(int base, int time)

圆括号内的变量 basetime 称为形式参数。这里的参数名称是必要的,且只在 power 内部有效。因此如果定义了多个函数,其他函数也可以使用与之相同的参数名。

main 函数里对定义的 power 函数进行调用:

printf("2^(%d)\t=%6d\n", i, power(2, i));

调用函数时传递给函数的参数的类型和数量必须和函数定义一致。

/* 下面操作将引发错误 */
/* expected ‘int’ but argument is of type ‘char *’ */
power("cx", 4);

函数调用中与形式参数对应的值称为实际参数。power 函数通过 return 语句将结果返回给 main 函数。return 后面可以是任何表达式。

对于没有返回值的函数,则不需要 return 语句。程序执行到函数的右终结括号就结束对该函数的执行,相应的函数的返回值类型应该是 void:

void func() {    // 参数列表也不是必要的
    printf("Hello, world!\n");
}

由于 power 函数的定义出现在 main 函数之后,因此在 main 函数之前还必须要有 power 函数的声明,这种声明称为 函数原型

int power(int base, int time);

函数原型必须与函数定义一致,除了参数名称,事实上,写成下面这样也是可以的(但是不建议):

int power(int, int);

/* 或者是下面这样 */
int power(int m, int n);

若没有显式指定返回参数类型,则默认返回 int

编译运行结果:

$ ./power.out 
2^(1)   =     2
2^(2)   =     4
2^(3)   =     8
2^(4)   =    16
2^(5)   =    32
2^(6)   =    64
2^(7)   =   128
2^(8)   =   256
2^(9)   =   512
2^(10)  =  1024
$ 

你可能感兴趣的:(C 笔记九 求幂函数)