原理,穷举生成N-1位定点二进制小数(第N位为1),然后转换成十进制的就行了。
import java.util.Scanner; public class GetDecimal { static Vector<int[]> record = null; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("输入n,输出n位可被浮点数精确表示的小数"); int len = sc.nextInt(); if (len == 1) System.out.println(0.5); else f(len - 1); } public static void f(int len) { double dec = 0; int max = (int) Math.pow(2, len) - 1; for (int i = 0; i <= max; i++) { dec = getSum(getBinString(i, len) + "1"); System.out.println(dec); } } // 转换成二进制字符串 public static String getBinString(int i, int len) { StringBuffer str = new StringBuffer(Integer.toString(i, 2)); for (int j = 0; str.length() != len; j++) { str.insert(0, "0"); } return str.toString(); } // 计算值 public static double getSum(String s) { double sum = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '1') { sum += Math.pow(2, -(i + 1)); } } return sum; } }