从用户读取基值和指数值。将基数本身乘以基数,再将结果乘以基数(再次)重复n次,其中n是指数值。
2 ^ 5 = 2 X 2 X 2 X 2 X 2 (5 times)
import java.util.Scanner; public class PowerOfNumber { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the base number ::"); int base = sc.nextInt(); int temp = base; System.out.println("Enter the exponent number ::"); int exp = sc.nextInt(); for (int i=1; i<exp; i++){ temp = temp*temp; } System.out.println("Result of "+base+" power "+exp+" is "+temp); } }
输出结果
Enter the base number :: 12 Enter the exponent number :: 2 Result of 12 power 2 is 144