zoukankan      html  css  js  c++  java
  • 剑指Offer面试题:10.数值的整数次方

    一 题目:数值的整数次方

    题目:实现doble Power(double base, int exponent),求basede exponent次方。不得使用库函数,同时不需要考虑大数问题。

    二 实现思路

      (1)当指数为负数的时候:可以先对指数求绝对值,然后算出次方的结果之后再取倒数

      (2)当底数(base)是零且指数是负数的时候:通过全局代码或异常告诉调用者参数有误

      (3)0的0次方的时候:由于0的0次方在数学上是没有意义的,因此无论是输出0还是1都是可以接受的。

    三 代码实现

    #include <math.h>
    
    bool Equal(double num1, double num2)
    {
        if (num1 - num2 > -0.0000001 &&
            num1 - num2 < 0.0000001)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    // 基数为base为double类型,exponent为整数
    double Power(double base, int exponent) throw(char *)
    {
        // 当底数为0且指数为负数时抛出异常
        if (Equal(base,0.0) && (exponent < 0))
        {
            throw "base must be positive!";
        }
        double dbResult = 1.0;
        if (exponent >= 1)
        {
            for (int i = 0; i < exponent; i ++)
            {
                dbResult *= base;
            }
        }
        else if (exponent < 0)
        {
            for (int j = 0; j < abs(exponent); j ++)
            {
                dbResult *= base;
            }
            dbResult = 1/dbResult;
        }
        else if(exponent == 0)
        {
            dbResult = 1;
        }
        return dbResult;
    }
    
    void main()
    {
        try
        {
            cout << Power(0,1) << endl;
            cout << Power(2, 3) << endl;
            cout << Power(-2, 3) << endl;
            cout << Power(2, -3) << endl;
            cout << Power(2, 0) << endl;
            cout << Power(0,-1) << endl;
        }
        catch (char *pError)
        {
            cout << pError << endl;
        }
        
        return;
    }

    细节:在判断底数base是不是等于0时,不能直接写base==0,这是因为在计算机内表示小数时(包括float和double型小数)都有误差。判断两个小数是否相等,只能判断它们之差的绝对值是不是在一个很小的范围内。如果两个数相差很小,就可以认为它们相等。
  • 相关阅读:
    httpclient5:信任所有证书,调用公众号接口
    驾驶技能考试系统:常见故障原因分析及排除
    C#:Combox实现key,value
    C#:密码框的两种方式
    C#:动态添加或删除控件,并根据控件名称获得控件
    微服务设计模式
    微服务设计模式
    微服务设计模式
    微服务设计模式
    微服务设计模式
  • 原文地址:https://www.cnblogs.com/xiaobingqianrui/p/8855611.html
Copyright © 2011-2022 走看看