高精度问题——Java大数类~系列7——浮点数进制转换 hdu 1376
高精度问题(7)——浮点数进制转换
题目大致要求就是将任意八进制浮点数转换为十进制数,用Java大数类实现。
hdu 1376 原题如下:
Octal Fractions
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 223 Accepted Submission(s): 125
Problem Description
Fractions in octal (base 8) notation can be expressed exactly in decimal notation. For example, 0.75 in octal is 0.963125 (7/8 + 5/64) in decimal. All octal numbers of n digits to the right of the octal point can be expressed in no more than 3n decimal digits to the right of the decimal point.
Write a program to convert octal numerals between 0 and 1, inclusive, into equivalent decimal numerals. The input to your program will consist of octal numbers, one per line, to be converted. Each input number has the form 0.d1d2d3 ... dk, where the di are octal digits (0..7). There is no limit on k. Your output will consist of a sequence of lines of the form
0.d1d2d3 ... dk [8] = 0.D1D2D3 ... Dm [10]
where the left side is the input (in octal), and the right hand side the decimal (base 10) equivalent. There must be no trailing zeros, i.e. Dm is not equal to 0.
Write a program to convert octal numerals between 0 and 1, inclusive, into equivalent decimal numerals. The input to your program will consist of octal numbers, one per line, to be converted. Each input number has the form 0.d1d2d3 ... dk, where the di are octal digits (0..7). There is no limit on k. Your output will consist of a sequence of lines of the form
0.d1d2d3 ... dk [8] = 0.D1D2D3 ... Dm [10]
where the left side is the input (in octal), and the right hand side the decimal (base 10) equivalent. There must be no trailing zeros, i.e. Dm is not equal to 0.
Sample Input
0.75
0.0001
0.01234567
Sample Output
0.75 [8] = 0.953125 [10]
0.0001 [8] = 0.000244140625 [10]
0.01234567 [8] = 0.020408093929290771484375 [10]
代码如下:
1 //7.大数进制转换 ~java~ hdu 1376 2 import java.math.BigDecimal; 3 import java.util.Scanner; 4 import java.io.*; 5 6 pubilc class Main 7 { 8 public static void main(String[] args) 9 { 10 String a; 11 BigDecimal eight=new BigDecimal(8); 12 Scanner cin = new Scanner(System.in); 13 while(cin.hasNext()) 14 { 15 a=cin.nextLine(); 16 BigDecimal ans=new BigDecimal(0); 17 BigDecimal tmp=new BigDecimal(1); 18 for(int i=2;i<a.length();i++) 19 { 20 tmp=tmp.divide(eight); 21 ans=ans.add(new BigDecimal(a.charAt(i)-'0').multiply(tmp)); 22 //charAt(i)取字符串中第i个,并返回;若没有对应位,返回"" 23 } 24 System.out.println(a+" [8] = "+ans.stripTrailingZeros().toPlainString()+" [10]"); 25 } 26 } 27 }
2013-8-11
晴
浙公网安备 33010602011771号