| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 876 人关注过本帖
标题:java中的“%”问题
只看楼主 加入收藏
guozong3
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2004-10-17
收藏
 问题点数:0 回复次数:2 
java中的“%”问题

计算时结果与书上的不一致

……

double a=18.4;

double b=a%4;

……

运行结果

b= 2.3999999999999986

(13个9)而书上给的结果是

b=2.4

请问这是怎么回事?是书上错了吗?

搜索更多相关主题的帖子: java 
2004-10-18 15:36
helloworld
Rank: 1
等 级:新手上路
帖 子:185
专家分:0
注 册:2004-8-27
收藏
得分:0 
这个应该是浮点数的精度问题。浮点数是不精确的。若要精确计算,建议你使用BigDecimal,它的精度是最高的
BigDecimal a = new BigDecimal(18.4);
BigDecimal b = a.divide(a,2,2);
结果:2.40
如果你需要3位小数,则改为:
BigDecimal b = a.divide(a,3,2);

2004-11-01 12:35
Anstey
Rank: 1
等 级:新手上路
帖 子:94
专家分:0
注 册:2004-4-14
收藏
得分:0 

A floating point number(float,double), the calculation of them is SELDOM exact.

A simple example would be a float variable, a float variable is a 32-bit signed variable that contains 3 parts:

a sign-bit which is used to represent the sign of the number: 0 (positive), 1 (nagetive)

a 8 bit exponent field, this decides the range of the variable, a exponent is represented as unsigned(sign and maginitude) and use a bias of 127. 1000 0001 will be actually 8*16 + 1 = 129 - 127 = 2, so the actual expoent is 2^2;

a 23-bit sigificand, which decides the presesion of the variable, this is the main part of your question, the calculation is seldom exact because the field to represent the "precision" is limited, and it is not possible to represent it exactly as what it is, so flaoting number calculation always round value to give a NOT exact , but exact enough in the sense how we need them.

I know I have made you very confused now, just remember, floating number Arithematic is seldom exact. Since the way they are built up are "complicated" as i described above.

an example of floating point number;

float f = - 3.5;

//look at the actual bits

- 3.5 = 1100 0000 0110 0000 0000 0000 0000 0000 (0xC0600000)


Anstey. Cheers. I love CAPPUCCINO~~
2004-11-05 17:47
快速回复:java中的“%”问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016806 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved