9.1 函数的定义与调用
9.1.1 程序:计算平均值
#include <stdio.h>float ave(float a,float b);int main(){float a = 5.0;float b = 2.0;a = ave(a,b);printf("%.2f",a);}float ave(float a,float b){return (a+b)/2;}// 输出3.50
9.1.2 倒数计时
#include <stdio.h>#include <windows.h>void Countdown(int a);int main(){for(int j=10;j>0;j--){Countdown(j);// Sleep(DWORD dwMilliseconds) 是一个存在于// windows.h 中的延时函数,其参数是毫秒// 注意 Sleep 是大写Sleep(1000);}}void Countdown(int a){printf("%d\n",a);}// 输出(延时效果)10987654321
9.1.5 函数调用
void 类型的函数调用是语句,非 void 类型的函数调用表达式,存储在变量中,或者进行测试等
// voidprint_count(i);// 非 void 的用处很多avg = average(x,y);
9.2 函数声明
我们既可以把其他函数放在 main 之前,也可以放在 main 之后,但是放在 main 之后需要对其他函数进行声明,否则在程序进行到 main 函数时(main 的某一步读取你的函数)会找不到你的函数。
// 其他函数放在 main 之前#include <stdio.h>float ave(float a,float b){return (a+b)/2;}int main(){float a = 5.0;float b = 2.0;a = ave(a,b);printf("%.2f",a);}// 输出3.50// 其他函数放在 main 之后,需要声明#include <stdio.h>// 这就是函数的声明,声明的函数参数依旧是形式参数float ave(float a,float b);int main(){float a = 5.0;float b = 2.0;a = ave(a,b);printf("%.2f",a);}float ave(float a,float b){return (a+b)/2;}// 输出3.50
9.3 实际参数
9.3.2 数组作为实际参数
- 由于 C 语言的特性,数组作为实际参数通常可以不说明数组的长度,而且通常的做法是把数组的长度额外的提供出来
#include <stdio.h>int sum(int a[],int len);int main(){int a[] = {1,2,3,4,5};// 在传递数组实参的时候,只写数组名,不加 []int b = sum(a,5);printf("%d ",b);}int sum(int a[],int len){int sum=0;for(int i=0;i<len;i++){sum+=a[i];}}// 输出5
9.4 return 语句
#include <stdio.h>int main(){return 0;int a[] = {1,2,3,4,5};int b = a[1];printf("%d ",b);}// 无输出,return 语句可以立即返回函数(结束),不再进行其他的步骤
9.5 程序终止
除了使用 return,还可以使用 stdlib.h 中的 exit 语句,其中 EXIT_SUCESS 和 EXIT_FAILUER 是定义在其中的宏
