溢出注意:
2的62次方、3的39次方、...、10的18次方、20的14次方...
代码如下:
package example;
//JHTP Exercise 6.14: Exponentiation
//by pandenghuang@163.com
/**(Exponentiation) Write a method integerPower(base, exponent) that returns the value of
base exponent
For example, integerPower(3, 4) calculates 34 (or 3 * 3 * 3 * 3). Assume that exponent is a positive,
nonzero integer and that base is an integer. Use a for or while statement to control the calculation.
Do not use any Math class methods. Incorporate this method into an application that reads
integer values for base and exponent and performs the calculation with the integerPower method.*/
import java.util.Scanner;
public class Exponentiation
{
public static long IntegerPower(int base,int exponent){
long result=1;
for (int i=0;i<exponent;i++)
result*=base;
return result;
}
public static void main(String[] args)
{
int base=0;
int exponent=1;
long result=0;
Scanner input=new Scanner(System.in);
do {
System.out.print("请输入基数(输入-1退出):");
base=input.nextInt();
if(base==-1)
System.out.print("已退出程序");
else
{
System.out.print("请输入指数:");
exponent=input.nextInt();
result=IntegerPower (base,exponent);
System.out.printf("%d的%d次方的值为:%d\n",base,exponent,result);
}
}
while (base!=-1);
}
}
运行结果:
请输入基数(输入-1退出):2
请输入指数:62
2的62次方的值为:4611686018427387904
请输入基数(输入-1退出):3
请输入指数:39
3的39次方的值为:4052555153018976267
请输入基数(输入-1退出):3
请输入指数:40
3的40次方的值为:-6289078614652622815
请输入基数(输入-1退出):10
请输入指数:18
10的18次方的值为:1000000000000000000
请输入基数(输入-1退出):20
请输入指数:14
20的14次方的值为:1638400000000000000
请输入基数(输入-1退出):-1
已退出程序