double 精度问题

/**
*相传国际象棋是古印度舍罕王的宰相达依尔发明的。
*舍罕王十分喜欢,决定让宰相自己选择赏赐。
*这位宰相指着8×8共64格的棋盘说:陛下,请您赏给我一些麦子吧,
*在棋盘的第一个格子放1粒,第2格放2粒,第3格放4粒,
*以后每一格都比前一格增加一倍,依此放完棋盘上的64个格子,我就感恩不尽了。
*舍罕王让人扛来一袋麦子,他要兑现他的许诺。国王能兑现他的许诺吗?
*/

import java.text.DecimalFormat;
import java.math.*;

public class a{
public static void main(String[] args){
Double a2 = new Double("0");
double a=0L;
long b=0;
for (int i=1; i<=64 ; i++ ){
//计算过程.
b= (long)Math.pow(2, i-1); //2的i-1次方.
a += b ;
a2 +=b ;
System.out.println("第"+i+"格麦子数:"+b+" 累加:"+a);
}
 //double 转成 String
DecimalFormat decimalFormat = new DecimalFormat("#");
System.out.print("\n最终累加结果:");
System.out.println(decimalFormat.format(a));
BigDecimal a1 = new BigDecimal(Double.toString(a));
System.out.println(a1);
System.out.println(new DecimalFormat("0.00").format(a));
System.out.println(new BigDecimal(a+""));

java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
nf.setGroupingUsed(false);
System.out.println(nf.format(a2));
System.out.println(new BigDecimal(Double.toString(a2)));
}
}

猜你喜欢

转载自www.cnblogs.com/agzno1hb/p/9061797.html