数值的整数次方

it2022-05-05  129

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方

public class Solution { static boolean b = false; public double Power(double base, int exponent) { if (equal(base, 0)) { return 0; } if (base < 0) { //底数为负数 if (exponent % 2 == 0) { //偶数个 base = -base; } } if (exponent < 0) { exponent = -exponent; b = true; } return CyclicComputation(base, exponent); } public double CyclicComputation(double base, int exponent) { double text = 1; while (exponent > 0) { text *= base; exponent--; } if (b) { text = (1 / text); } return text; } //判断base是否为0,在计算机内表示小数时都有误差,判断两个小数是否相等,判断它两之差的绝对值是否在一个很小的范围内即可 public boolean equal(double base, int m) { double temp = base - m; return temp > -0.0000001 && temp < 0.0000001; } }

 


最新回复(0)