n的m次方的计算(Exponentiation)

溢出注意:

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
已退出程序



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值