如何求一个数的指定次方根?含双参数函数实现需求
计算指定数字的n次根的函数实现
核心逻辑
计算数字的n次根,本质是求该数字的1/n次方,通过幂运算即可完成。同时需要处理两类无效输入:非正的根次数、负数的偶次根(实数范围内无意义)。
Python 实现示例
def calculate_nth_root(number, root_degree): if root_degree <= 0: raise ValueError("根次数必须是正整数") if number < 0 and root_degree % 2 == 0: raise ValueError("负数的偶次根在实数范围内不存在") return number ** (1 / root_degree)
调用示例
计算4的五次根:
result = calculate_nth_root(4, 5) print(result) # 输出约 1.3195079107728942
JavaScript 实现示例
function calculateNthRoot(number, rootDegree) { if (rootDegree <= 0) { throw new Error("根次数必须是正整数"); } if (number < 0 && rootDegree % 2 === 0) { throw new Error("负数的偶次根在实数范围内不存在"); } return Math.pow(number, 1 / rootDegree); }
调用示例
计算4的五次根:
const result = calculateNthRoot(4, 5); console.log(result); // 输出约 1.3195079107728942
内容的提问来源于stack exchange,提问作者Younes Vesey
相关产品推荐
相关产品推荐

