Java中的双增量

编程入门 行业动态 更新时间:2024-10-26 18:18:51
本文介绍了Java中的双增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 如何在0.1f和1.0f之间迭代,0.1f增量在Java?

我的程序的一部分需要在while循环中使用值:

0.1

0.2

0.3

...

0.9

所以我需要将它们提供给该循环。 这里是代码:

double x = 0.0; while(x< = 1) { //为每次迭代增加x为0.1 x + = 0.1; }

我需要输出是完美的: / p>

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

但实际上给我的东西就像:

0.1

0.2

0.300000000000000000000000004

0.4

0.5

0.6

0.799999999999999999999999

0.899999999999999999999999

0.999999999999999999999999

解决方案

欢迎来到浮点世界,其中0.1不为0.1。问题是许多数字,包括0.1,不能在 double 中正确表示。所以你每次都不会在循环中真正地添加0.1到 x 。

一种方法是使用整数算术除以10:

int i = 0; while(i< = 10){ double x = i / 10.0; 。 。 。 i ++; }

另一种方法是使 x a BigDecimal ,您可以在其中指定您想要的特定精度。它基本上是做上述循环所做的(一个整数加一个比例),但是打包在一个很好的类中,有很多的响铃和口哨。哦,它有任意的精确度。

Possible Duplicate: How to iterate between 0.1f and 1.0f with 0.1f increments in Java?

Part of my program needs to use values inside a while loop as:

0.1

0.2

0.3

...

0.9

so I need to provide them inside that loop. Here is the code:

double x = 0.0; while ( x<=1 ) { // increment x by 0.1 for each iteration x += 0.1; }

I need the output to be EXACTLY:

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

But it actually gives me something like:

0.1

0.2

0.300000000000000000000000004

0.4

0.5

0.6

0.79999999999999999999999999

0.89999999999999999999999999

0.99999999999999999999999999

解决方案

Welcome to the world of floating point, where 0.1 isn't 0.1. The problem is that many numbers, including 0.1, cannot be represented exactly in a double. So you aren't really adding exactly 0.1 to x each time through the loop.

One approach is to use integer arithmetic and divide by 10:

int i = 0; while (i <= 10) { double x = i / 10.0; . . . i++; }

Another approach is to make x a BigDecimal, where you can specify that you want a particular precision. It basically is doing what the above loop does (an integer plus a scale), but packaged up in a nice class with lots of bells and whistles. Oh, and it has arbitrary precision.

更多推荐

Java中的双增量

本文发布于:2023-11-30 10:02:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649589.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!