例 1, 实现 pow 函数并尝试.
验证头文件:#include <math.h>
pow() 函数用来求 x 的 y 次幂 (次方),x,y 及函数值都是 double 型 , 其原型为:
double pow(double x, double y);
pow() 用来计算以 x 为底的 y 次方值, 然后将结果返回.
直接调用库函数:
- include <stdafx.h>
- #include<stdio.h>
- #include<math.h>
- void main()
- {
- double x=2.0,y=3.0,z;
- z = pow (x,y);
- printf("%lf to the power of %lf is %lf\n",x,y,z);
- }
自己定义函数:
- #include <stdafx.h>
- #include<stdio.h>
- void main()
- {
- double pow(double x,double y);
- double x=2.0,y=3.0,z;
- z = pow (x,y);
- printf("%lf to the power of %lf is %lf\n",x,y,z);
- }
- double pow(double x,double y)
- {
- double z=1;
- for(;y>0;y--)
- {
- z*=x;
- }
- return z;
- }
注: 新增变量最好赋初值, 否则系统会随机给它一个值.
例 2: 猜想 sqrt() 函数的原理并尝试编程.(暂时只要求整型数据)
- #include <stdafx.h>
- #include<stdio.h>
- void main()
- {
- int sqrt(int x);
- int x=49,z;
- z = sqrt (x);
- if(x<0)
- printf("Error:sqrt returns %d\n",x);
- else
- printf("%d\n",z);
- }
- int sqrt(int x)
- {
- int temp=1;
- while(1)
- {
- if(temp*temp==x)
- return temp;
- else
- ++temp;
- }
- }
来源: http://www.bubuko.com/infodetail-2940142.html