在Java中分割双精度的奇怪行为 [英] Odd behaviors when dividing doubles in Java

查看:134
本文介绍了在Java中分割双精度的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 双b = 317/219; 
System.out.println(b);

输出是:1。



是这是因为它是一个重复的小数?
不必使用BigDecimal,这是令人讨厌的。

解决方案

尝试这个

 双b = 317 / 219D; 

java中的编码数字的默认类型是 int ,所以随着你的代码,java正在使用两个 int 数字,然后分割的结果将是 int ,这将截断小数部分以给出 1 的最终结果。然后将 int 结果从 int 1 转换为 double 1 没有编译器警告,因为它是一个扩展转换(一个源类型被保证适合到目标类型中)。



通过将数字编号为 double 与尾随 D (您也可以使用 d ,但我总是使用大写字母,因为 L 为小写 l 看起来像 1 ),分区的结果也将是 double


When I divide 317 by 219 in Java using doubles I get 1.
For example:

double b = 317/219;
System.out.println(b);

Output is: 1.

Is this because it is a recurring decimal? Have had to use BigDecimal instead which is annoying.

解决方案

Try this

 double b = 317/219D;

The default type of coded numbers in java is int, so with the code as you have it java is working with two int numbers and the result of the division would then be int too, which will truncate the decimal part to give a final result of 1. This int result is then cast from int 1 to a double 1 without a compiler warning because it's a widening cast (one where the source type is guaranteed to "fit" into the target type).

By coding either of the numbers as double with the trailing D (you may also use d, but I always use upper case letters because L as lowercase l looks like a 1), the result of the division will be double too.

这篇关于在Java中分割双精度的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆