本文介绍了使用BigDecimal计算PI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我第一次使用BigDecimal,但遇到了一些麻烦.
This is my first time using a BigDecimal and I am having some troubles with it.
这是我的代码:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
BigDecimal pi = new BigDecimal(4);
boolean plus = false;
for (int i = 3; i < 1000000; i += 2) {
if (plus) {
pi.add(new BigDecimal(4).divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP));
} else {
pi.subtract(new BigDecimal(4).divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP));
}
plus = !plus;
}
System.out.println(pi);
}
}
为什么它没有像应该那样计算PI,却给了我4个答案?
Why doesn't it calculate PI like it should but instead it gives me and answer of 4?
推荐答案
您永远不会更改pi.请记住,BigDecimals是不可变的,并且您永远都不会更改自己的值,即,您永远不会将其分配给新值,因此您必须在某个地方
You never change pi. Remember that BigDecimals are immutable, and you never change yours, i.e., you never assign it to a new value, and so you have to have somewhere
pi = ...
在您的if/else里面是个不错的地方.
Inside your if/else would be a good place for this.
if (plus) {
pi = pi.add(new BigDecimal(4).divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP));
} else {
pi = pi.subtract(new BigDecimal(4).divide(new BigDecimal(i), 2, BigDecimal.ROUND_HALF_UP));
}
我还将将2的比例更改为更好的水平.
I would also change that scale of 2 to something better.
这篇关于使用BigDecimal计算PI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!