【问题标题】:BigDecimal.valueOf(n).toPlainString() is not giving exact valueBigDecimal.valueOf(n).toPlainString() 没有给出确切的值
【发布时间】:2014-08-08 09:36:33
【问题描述】:

我正在获取一个双精度值(由不同的方法生成),我想从中提取尾随零的数量。一种方法是将其转换为字符串,然后对其进行操作,但我正在获取值科学记数法,例如该方法生成的阶乘为 60,即 8.320987112741392E81,因为它采用科学记数法,我无法对其进行字符串操作。我对此进行了谷歌搜索,发现使用 BigDecimal.valueOf(n).toPlainString() 我可以得到确切的数字,但不幸的是我得到了这个 //8320987112741392000000000000000000000000000000000000000000000000000000000000000000 而正确的准确答案是 //8320987112741390144276341183223364380754172606361245952449277696409600000000000000

任何人都知道如何解决这个问题

public class Factorial {

public static void main(String[] args) throws IOException {

    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    int t = Integer.parseInt(bf.readLine());
    for (int i = 0; i < t; i++) {
        double num = Double.parseDouble(bf.readLine());
        System.out.println("fact ans" + factorial(num));
        System.out.println(z(factorial(num)));
    }

}

public static Double factorial(Double n) {
    if (n < 2) {
        return 1D;

    }
    return n * factorial(n - 1);

}

public static int z(Double n) {

    System.out.println(BigDecimal.valueOf(n).toPlainString());
    return 1;

}

}

【问题讨论】:

  • 如果你想要一个确切的数字,为什么要使用双精度数?众所周知,像 double 这样的浮点数是不精确的。
  • 所以我想我应该使用 long 吗?
  • 不,您应该使用 BigDecimal。

标签: java biginteger bigdecimal


【解决方案1】:

您将阶乘存储在 Double 类型中。显然,n 的大值是不精确的(因为它是浮点类型)。将不精确的值转换为 BigDecimal 无法使其精确。如果你想得到精确的阶乘值,你最好使用BigInteger

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多