求高精度幂
Description:
Problems involving the computation of exact values of very large magnitude and precision are common. For example, the computation of the national debt is a taxing experience for many computer systems.
This problem requires that you write a program to compute the exact value of Rn where R is a real number ( 0.0 < R < 99.999 ) and n is an integer such that 0 < n <= 25.
Input:
The input will consist of a set of pairs of values for R and n. The R value will occupy columns 1 through 6, and the n value will be in columns 8 and 9.
Output:
The output will consist of one line for each line of input giving the exact value of R^n. Leading zeros should be suppressed in the output. Insignificant trailing zeros must not be printed. Don’t print the decimal point if the result is an integer.
Sample Input:
95.123 12
0.4321 20
5.1234 15
6.7592 9
98.999 10
1.0100 12
Sample Output:
548815620517731830194541.899025343415715973535967221869852721
.00000005148554641076956121994511276767154838481760200726351203835429763013462401
43992025569.928573701266488041146654993318703707511666295476720493953024
29448126.764121021618164430206909037173276672
90429072743629540498.107596019456651774561044010001
1.126825030131969720661201
代码块
import java.util.*;
import java.math.BigDecimal;
public class Main{
public static void main(String[] args){
Scanner cin=new Scanner(System.in);
BigDecimal a;
int b;
while(cin.hasNext()){
a=cin.nextBigDecimal();
b=cin.nextInt();
a=a.pow(b);//求a的b次方
//传换成字符串,如果是整数,去掉小数点和后面的
String res=a.stripTrailingZeros().toPlainString();
//如果是o开头的,去点前导o
if(res.startsWith("0")){
res=res.substring(1);
}
System.out.println(res);
}
}
}
关于调用的一些方法解释:
1 hasNext():判断是否有数据输入。
2 使用BigDecimal原生方法实现末尾去0
有这么一个需求,一个BigDecimal值,四舍五入计算到小数点后4位,如果小数点后3、4位是0则去掉,保留到小数点后两位
即20.00345 显示成20.0035
20 显示 20.00
20.00395 显示 20.004
发现BigDecimal原生提供了stripTrailingZeros方法可以实现去掉末尾的0,然后使用toPlainString可以输出数值,注意这里如果使用toString() 会变成科学计数法输出
但对于要保留两位小数0的情况这里会变成显示20,即不带小数点后两位,只能通过字符串判断加上,难看点但算是实现了这个偏门的需求。
3 substring(1):返回一个新的字符串,这个字符串为原来的子字符串,从位置1开始截取。