- C语言中,函数(function)是用来模块化构建程序的。
- 可以编写一个具有特定功能的函数,然后在一个程序的多个地方使用它(即自定义函数)。
- 数学函数库可以实现某种常用的数学运算,若使用数学函数库,需使用预编译命令#include<math.h>将数学库头文件包含进来。
double result = sqrt(900.0);
//一些常用数学库函数
sqrt(x) x的平方根
cbrt(x) x的立方根
exp(x) 指数函数
log(x) 对数函数(以e为底)
log10(x) 以10为底的对数函数
fabs(x) 以浮点数表示的x的绝对值
ceil(x) 向上取整
floor(x) 向下取整
pow(x,y) x的y次幂
fmod(x,y) 以浮点数表示的x/y的余数
sin(x) 正弦
cos(x) 余弦
tan(x) 正切
4.所有在函数内部定义的变量都称为局部变量,他们只能在定义他们的函数内部访问,绝大多数函数都有一个形式参数的列表。
//用square函数来计算打印1~10十个整数的平方
//
#include <stdio.h>
int square(int y); // function prototype 函数原型/函数声明
int main(void)
{
// loop 10 times and calculate and output square of x each time
for (int x = 1; x <= 10; ++x) {
printf("%d ", square(x)); // function call 这一行调用的square函数
}
puts("");
}
// square function definition returns the square of its parameter
int square(int y) // y is a copy of the argument to the function
{
return y * y; // returns the square of y as an int
}
常见错误:即使若干个形参的数据类型是相同的,也应该分别定义,例如double x,double y
如果图省事将其写成 double x,y
,将导致一个编译错误。
//利用自定义函数maximum来确定三个整数中的最大者并将其返回
#include <stdio.h>
int maximum(int x, int y, int z); // function prototype 函数原型
int main(void)
{
int number1; // first integer entered by the user
int number2; // second integer entered by the user
int number3; // third integer entered by the user
printf("%s", "Enter three integers: ");
scanf("%d%d%d", &number1, &number2, &number3);//输入三个整数
// number1, number2 and number3 are arguments
// to the maximum function call
printf("Maximum is: %d\n", maximum(number1, number2, number3));
}
// Function maximum definition
// x, y and z are parameters
int maximum(int x, int y, int z)
{
int max = x; // assume x is largest
if (y > max) { // if y is larger than max,
max = y; // assign y to max
}
if (z > max) { // if z is larger than max,
max = z; // assign z to max
}
return max; // max is largest value
}
使用头文件<stdlib.h>中定义的C标准库函数rand()
//模拟掷骰子20次并打印
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// loop 20 times
for (unsigned int i = 1; i <= 20; ++i) {
// pick random number from 1 to 6 and output it
printf("%10d", 1 + (rand() % 6));
//通过 1 + rand() % 6 来平移和缩放随机生成的整数
// if counter is divisible by 5, begin new line of output
if (i % 5 == 0) {
puts("");
}
}
}
严格地说,函数rand产生的是伪随机数,反复调用函数rand,是会得到一系列看上去随机出现的整数,但是重复执行这个程序,这一列整数将重复出现。
递归函数就是直接或通过其他函数间接的调用自己的函数。
递归和迭代都分别以一种控制结构为基础:迭代基于循环结构,而递归基于选择结构。
(任何一个可以用递归方法解决的问题,都可以用迭代(非递归)的方法求解)
递归有很多缺点:……