程序练习 输入两个整数,计算他们的和并输出 采用自定义函数
程序练习 输入两个整数,计算他们的和并输出, 采用自定义函数
7.4函数的调用 ★调用形式 #include <stdio.h> 函数名(实参表) int f(int a, int b) 1、实参与形参个数相等,类 i int c: 型一致,按顺序一一对应; if(a>b)c=l; 2、如果调用无参函数,则实 参表可以省略,但括号不能 else if(a==b)c=0; 省 else c=-1 3、实参表求值顺序,因系统 return c; 9 而定,一般是从右向左,为 避免由此引起的混乱,一般 void maino 应在调用函数前计算出实参{inti=2, 的值。 p=f(i,++); printf(%d”,yp);}
调用形式 函数名(实参表) 1、实参与形参个数相等,类 型一致,按顺序一一对应; 2、如果调用无参函数,则实 参表可以省略,但括号不能 省; 3、实参表求值顺序,因系统 而定,一般是从右向左,为 避免由此引起的混乱,一般 应在调用函数前计算出实参 的值。 #include <stdio.h> int f(int a,int b) { int c; if(a>b) c=1; else if(a==b) c=0; else c=-1; return c;} void main() { int i=2,p; p=f(i,++i); printf(“%d”,p);} 7.4 函数的调用
★调用方式 ◆函数语句: 例 printstar(O printf("I am a student!\n); 说明:这种方式不要求函数带回返回值,仅完成 定的操作; ◆函数表达式: 例m=max(a,b)*2; 说明:这种调用方式不能用于void型函数 ◆函数参数: 例 printf(“%d”max(a,b); m=max( a, max(b, c))
调用方式 ❖函数语句: 例 printstar(); printf(“I am a student!\n”); 说明:这种方式不要求函数带回返回值,仅完成一 定的操作; ❖函数表达式: 例 m=max(a,b)*2; 说明:这种调用方式不能用于void型函数; ❖函数参数: 例 printf(“%d”,max(a,b)); m=max(a,max(b,c));
常用库函数 内量函数 头文件 用途 double sqrt(double x) 计算ⅹ的平方根 double pow(double x, 计算x的y次幂 double y) double ceil( double x) math. h求不小于x的最小整数,并以 double形式显示 double floor(double x) 求不大于X的最大整数,并以 double形式显示 int toupper(int x) 如果X为小写字母,则返回对应 int tolower(int x) cpeb/的大写字母 如果X为大写字母,则返回对应 的小写字母 int rand (void) stdlib.h产生一个随机数 void exit(int retval) 终止程序
常用库函数 内置函数 头文件 用途 double sqrt(double x) math.h 计算x的平方根 double pow(double x, double y) 计算x的y次幂 double ceil(double x) 求不小于x的最小整数,并以 double形式显示 double floor(double x) 求不大于x的最大整数,并以 double形式显示 int toupper(int x) ctype.h 如果x为小写字母,则返回对应 的大写字母 int tolower(int x) 如果x为大写字母,则返回对应 的小写字母 int rand(void) stdlib.h 产生一个随机数 void exit(int retval) 终止程序
内置函数sqrt和pow示例 求自然数1-5的平方根和立方。 include <stdio. h> include <math. h> 1的平方根:1.001的立方:1 void maino 2的平方根:1412的立方8 3的平方根:1733的立方:27 4的平方根2.004的立方:64 int x1 5的平方根:2245的立方:125 double squareroot, power; Press any key to continue for(X=1;X<=5;X++) squareroot=sqrt(x) power=pow(x, 3) print("‰d的平方根%321t%的立方:%50fn", x, squareroot, x, power)
求自然数1-5的平方根和立方。 内置函数sqrt 和pow 示例 2 6 64 #include <stdio.h> #include <math.h> void main() { int x=1; double squareroot,power; for(x=1;x<=5;x++) { squareroot=sqrt(x); power=pow(x,3); printf(" %d的平方根:%3.2f\t%d的立方:%5.0f \n", x,squareroot,x,power); } } 1的平方根: 1.00 1的立方: 1 2的平方根: 1.41 2的立方: 8 3的平方根: 1.73 3的立方: 27 4的平方根: 2.00 4的立方: 64 5的平方根: 2.24 5的立方: 125 Press any key to continue