高精度问题——Java大数类~系列4——大数幂(浮点数) hdu 1063
高精度问题(4)——浮点数求幂
大数的整数求幂问题用C++实现起来已经挺麻烦了。现在要求的是浮点数的幂,那就更麻烦了,所以还是要用Java大数类来做。
不同的是,要导入的包为java.math.BigDecimal,而非java.math.BigInteger;另外还要注意一些细节,像是 后导0 怎么去掉、如何控制输出的形式之类。
hdu 1063 原题如下:
Exponentiation
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5651 Accepted Submission(s): 1549
Problem 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.
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
代码如下(有详细的注释):
1 //4.大数幂运算 ~java~ hdu 1063 2 import java.math.BigDecimal; 3 import java.util.Scanner; 4 5 public class Main 6 { 7 public static void main(String[] args) 8 { 9 Scanner cin = new Scanner(System.in); 10 int n, i; 11 BigDecimal r, a; 12 BigDecimal one=new BigDecimal("1"); 13 while(cin.hasNextBigDecimal()) 14 { 15 r=cin.nextBigDecimal(); 16 n=cin.nextInt(); 17 a=one; 18 for(i=1;i<=n;i++) 19 a=a.multiply(r); 20 a=a.stripTrailingZeros(); 21 //用stripTrailingZeros()去除后导0(e.g. 1.220000中的4个0) 22 String str=a.toPlainString(); 23 //toPlainString()防止高精度表示成科学技术法(即,转换成朴素的字符串) 24 if(str.startsWith("0.")) 25 //startsWith()判断,如果是小数,则去掉小数点前面的0 26 str=str.substring(1); 27 //substring()字符串截取,此处是去掉整数位的0 (e.g. "unhappy".substring(2) returns "happy") 28 System.out.println(str); 29 } 30 } 31 }
2013-08-11
晴
浙公网安备 33010602011771号