The sword refers to the Offer interview questions: 10. The integer power of the value

Question 1: Integer Power of Numerical Values

Topic: To achieve doble Power(double base, int exponent), find the power of basede exponent. Library functions must not be used, and large numbers need not be considered.

Two realization ideas

  (1) When the exponent is negative: you can first calculate the absolute value of the exponent, and then take the reciprocal after calculating the result of the power .

  (2) When the base is zero and the exponent is negative: tell the caller that the parameter is wrong through global code or an exception .

  (3) When 0 to the 0th power: Since 0 to the 0th power is mathematically meaningless, it is acceptable to output either 0 or 1.

Three code implementation

#include <math.h>

bool Equal(double num1, double num2)
{
    if (num1 - num2 > -0.0000001 &&
        num1 - num2 < 0.0000001)
    {
        return true;
    }
    else
    {
        return false;
    }
}

// The base is of double type, and the exponent is an integer 
double Power( double  base , int exponent) throw ( char * )
{
    // Throw an exception when the base is 0 and the exponent is negative 
    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;
}

Details: When judging whether the base base is equal to 0, you cannot directly write base==0, because there are errors when representing decimals (including float and double decimals) in the computer . To judge whether two decimals are equal, we can only judge whether the absolute value of their difference is within a small range. Two numbers are considered equal if they differ by a small amount.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324472793&siteId=291194637