所以0.8125的二进制是0.1101)
import java.math.BigDecimal; import java.util.Scanner; public class H4 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); BigDecimal num = BigDecimal.valueOf(Double.parseDouble(input)); String output=""; trans(num,output); } public static void trans(BigDecimal num,String output) { num = num.multiply(BigDecimal.valueOf(2)); String tmp = num.toString().substring(0, 1);//取小数点前一位 output +=tmp; num=num.subtract(BigDecimal.valueOf(Double.parseDouble(tmp))); if(num.compareTo(BigDecimal.ZERO)==0||output.length()==10) {//如果num=0或者小数点后有10位就停止递归 System.out.println("0."+output); return; } trans(num,output); } }
原文地址:http://blog.csdn.net/sparktank/article/details/25596453