我是靠谱客的博主 拉长学姐,最近开发中收集的这篇文章主要介绍java %.1f,如何在Java中以0.1f的增量在0.1f和1.0f之间进行迭代?,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

I am having a following problem in Java - I need to iterate between 0.1f and 1.0f in 0.1f increments,so I would like my output to look like this:

0.1

0.2

0.3

0.4

...

0.9

Instead,when I do:

for(float i = 0.1f; i < 1f; i += 0.1f)

System.out.println(i);

I get

0.1

0.2

0.3

0.4

0.5

0.6

0.70000005

0.8000001

0.9000001

I imagine it has something to do with the way fractions are represented by a computer,but I would like to know why is this,and if there is anything I can do to stop it.

thanks.

解决方案

Use integers in your for loop to avoid repeated floating point math, which compounds floating-point errors.

for (int i = 1; i < 10; i++)

{

float f = (float) i / 10.0f;

System.err.println(f);

}

最后

以上就是拉长学姐为你收集整理的java %.1f,如何在Java中以0.1f的增量在0.1f和1.0f之间进行迭代?的全部内容,希望文章能够帮你解决java %.1f,如何在Java中以0.1f的增量在0.1f和1.0f之间进行迭代?所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(78)

评论列表共有 0 条评论

立即
投稿
返回
顶部