标签:浮点数 次方 elf 语法 power else png pre inf
题目
给定一个double类型的浮点数base和int类型的整数exponent,求base的exponent次方
保证base和exponent不同时为0。
1、用内置函数pow
语法:
class Solution: def Power(self, base, exponent): # write code here if base == 0: return 0 elif exponent == 0: return 1 elif base == 1: return 1 elif exponent == 1: return base else: return pow(base, exponent)
2、不用pow。分exponent>0和<0的情况
class Solution2: def Power2(self, base, exponent): # write code here if base == 0: return 0 elif exponent == 0 or base == 1: return 1 elif exponent == 1: return base else: result = 1 if exponent > 0: for i in range(exponent): result = result * base return result else: ab_exponent = exponent * (-1) # 先把exponent取正 for i in range(ab_exponent): result = result * base return 1.0/result
标签:浮点数 次方 elf 语法 power else png pre inf
原文地址:https://www.cnblogs.com/RebeccaG/p/12292867.html