gpt4 book ai didi

java - 使用 RoundingMode 对 BigDecimals 进行舍入?

转载 作者:行者123 更新时间:2023-12-02 11:35:49 27 4
gpt4 key购买 nike

目前我正在编写一个程序来计算数学常数。但是,我在舍入 BigDecimal 时遇到问题。一旦达到非终止小数 (1.6),就会抛出错误。我认为问题在于舍入线,但它也将其设置为正确的小数位数,但没有舍入它。我是 BigDecimals 的新手,所以我可能忘记了一些东西。代码和输出如下所示。谢谢!

这是我的代码:

package goldenratio;
import java.math.*;

public class GoldenRatio {
static BigDecimal now;
static BigDecimal before;
static BigDecimal phi;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
for(int i=1;i<=100;i++)
{
if(i==1)
{
now=BigDecimal.valueOf(1);
before=BigDecimal.valueOf(1);
phi=BigDecimal.valueOf(1);
}else
{
phi=(now.divide(before));
phi = phi.setScale(5, RoundingMode.HALF_UP);
BigDecimal oldBefore = before;
before=now;
now=now.add(oldBefore);
}
System.out.println(phi);
}
}

这是我的输出:

run:
1.00000
2.00000
1.50000
Exception in thread "main" java.lang.ArithmeticException: Non-terminating
decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1690)
at goldenratio.GoldenRatio.main(GoldenRatio.java:30)

最佳答案

参见ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

基本上,您可以将 rounding_mode 传递到 div 函数中。见下文:

import java.math.*;

public class GoldenRatio {
static BigDecimal now;
static BigDecimal before;
static BigDecimal phi;

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i == 1) {
now = BigDecimal.valueOf(1);
before = BigDecimal.valueOf(1);
phi = BigDecimal.valueOf(1);
} else {
phi = (now.divide(before, 5, RoundingMode.HALF_UP));
BigDecimal oldBefore = before;
before = now;
now = now.add(oldBefore);
}
System.out.println(phi);
}
}
}

关于java - 使用 RoundingMode 对 BigDecimals 进行舍入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48956276/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com