码迷,mamicode.com
首页 > 其他好文 > 详细

函数程序举例(初学者)

时间:2019-01-30 23:13:49      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:\n   clu   初学   次方   class   code   printf   头文件   整型   

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

 

函数程序举例(初学者)

标签:\n   clu   初学   次方   class   code   printf   头文件   整型   

原文地址:https://www.cnblogs.com/lvfengkun/p/10339807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!