Java实现数值求幂返回异常结果,求问题原因分析
Java数值求幂功能的错误分析与修复
问题根源
你的findPower方法存在核心逻辑错误,导致计算结果完全偏离预期:
- 循环中每次执行
x *= x,会让结果以平方的方式迭代增长,最终得到的是x^(2^n),而非目标的x^n。比如输入5和9时,代码实际计算的是5→25→625→...经过9次平方后,结果不仅错误,还会触发int类型溢出。 - 即使结果未溢出,逻辑错误也会导致输出异常。
修复方案
方案1:修正基础循环逻辑(适用于小幂次、结果不溢出场景)
新增变量存储结果,每次循环将结果乘以底数x,循环次数调整为n-1次(初始结果为x1,再乘n-1次得到xn):
import java.util.* ; import java.io.*; class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int n = sc.nextInt(); System.out.println((n==0)?1:findPower(x,n)); } static int findPower(int x,int n){ int result = x; // 初始是x^1,需再乘n-1次x得到x^n for(int i=1;i<n;i++){ result *= x; } return result; } }
方案2:用long避免整数溢出
如果需要处理更大的幂次,将结果类型改为long,避免int溢出:
import java.util.* ; import java.io.*; class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int n = sc.nextInt(); System.out.println((n==0)?1:findPower(x,n)); } static long findPower(int x,int n){ long result = x; for(int i=1;i<n;i++){ result *= x; } return result; } }
方案3:快速幂算法(高效处理大幂次)
对于较大的n,快速幂算法时间复杂度为O(logn),比普通循环更高效,同时减少不必要的计算:
import java.util.* ; import java.io.*; class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int n = sc.nextInt(); System.out.println((n==0)?1:findPower(x,n)); } static long findPower(int x,int n){ long result = 1; long base = x; while(n > 0){ // 幂次为奇数时,将结果乘上当前底数 if(n % 2 == 1){ result *= base; } // 底数平方,幂次减半 base *= base; n = n / 2; } return result; } }
验证结果
输入x=5、n=9时,正确结果为1953125,修复后的代码均可输出该正确值。
内容的提问来源于stack exchange,提问作者Anselum
相关产品推荐
相关产品推荐

