Integer power value 12

Title Description

Given a double base type and floating-point type int integer exponent. Seeking exponent of the power base.
Ensure the base and exponent are not simultaneously 0

Ideas analysis

Determining whether the first base-method, special circumstances and then determine the exponential of 0, then the power values ​​obtained, the cycle that multiplies the last negative final result according to the number of power.

Code

public double Power(double base, int exponent) {
    if (base == 0) {
        return 0;
    }
    double res = 1;
    if (exponent == 0) {
        return res;
    }
    int n = exponent > 0 ? exponent : -exponent;
    for (int i = 1; i <= n; i++) {
        res*=base;
    }
    return exponent >= 0 ? res : (1 / res);
}
Published 117 original articles · won praise 8 · views 3711

Guess you like

Origin blog.csdn.net/qq_34761012/article/details/104490617