您的位置:首页 > 其它

函数程序举例(初学者)

2019-01-30 22:07 176 查看

例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;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: