java 中任意两个int 型相除,结果为零~ 碉堡了


标签:
it |
分类: JAVA |
做一个300
解决办法:
new BigDecimal(300).divide(new BigDecimal(1700));
-------------------------------------------------------------------
数据的值,远超于int long double的表示范围了。
要用BigInteger 和BigDecimal这些大数据类型
-------------------------------------------------------------------
这样写才能对,BigDecimal 有很多方法
http://s6/middle/4e1e357dgc5128eb02515&690中任意两个int
还是基础不行哇,这个应该和计算机编译器啥的有关吧。。。
转int 型:
BigDecimal a=new BigDecimal(12.88); int b=a.intValue(); System.out.println(b);//b=12;
空大师 碉 啊
--------------------------------------------------------
13.2.17 补充:
转自:http://blog.csdn.net/love_world_/article/details/8478879
一
二 眼见为实,举例证明:
-
//
float与double 无法精确表示0.1 或者 10的负次方 -
System.out.println(
0.15 - 0.05); //0.09999999999999999 -
System.out.println(
2.08f - 3.7f); //-1.6200001
三 举一个现实中会遇到的情况:
-
10
- 0.9* 10= 1
-
float
myMoney 10.00f;= -
float
price 0.9f;= -
for
( inti 0;= i 10;< i++) { -
myMoney -= price; -
}
-
System.out.println(
myMoney ); // 1.0000002
四 解决办法
1. 使用int 和 long类型,如果小数点以后的值可以忽略不计可以只用这两种类型
2. 对计算结果进行四舍五入
3. 使用BigDecimal类型进行浮点运算
先来看一段代码
-
int
intValue 10;= -
float
floatValue 0.99999f;= -
-
int
count1 int)= ( (intValue + floatValue); -
System.out.println("10
+ 0.99999 = " + //count1); output 10 -
-
int
count2 int)= ( (intValue - floatValue); -
System.out.println("10
- 0.99999 = " + //count2); output 9
原本按我个人的理解
更深入的分析可以查看
如何解决float和double误差问题呢?可以使用Java中提供的java.math.BigDecimal,不过此类型是不可变的,每次计算都必须新创建一个对象,不适合大量计算
再来看一个舍入误差会出现的问题
-
10.1 + 0.99*10 = 20 -
float
f1 10.1f;= -
float
f2 0.99f;= -
for
( inti 0;= i 10;< i++) { -
f1 += f2; -
}
-
System.out.println(f1);
// 19.999998
解决办法,使用BigDecimal
-
BigDecimal
count new= BigDecimal( "10.1"); -
for
( inti 0;= i 10;< i++) { -
count = count.add(new BigDecimal( "1")); -
}
-
-
System.out.println(count.intValue());
// 20
参考资料:
2. 《Effective Java》 第2版 第48条 如果需要精确的答案,请避免使用float和double