Java的math.random查询,舍入(概念理解)

huangapple go评论84阅读模式
英文:

Java math.random query, rounding (concept understanding)

问题

我正在尝试理解math.random的逻辑,或者更具体地说,发生了什么以及为什么发生。

我理解,由于Java是一种以0为基础的语言,所以在索引等方面我们从0开始,如下面的代码所示,例如:

下面的代码会打印出一个介于0和10之间的值。
11是排除在外的,就像你理解的那样。

int result = (int) (Math.random() * 11);

我的问题是,为什么,例如,如果我们得到0.99 * 10然后等于10.99,为什么这个数字不会四舍五入到11?

这是否仅仅是Java的设计,总是向下舍入到0?还是我漏掉了某个概念?

感谢您的所有帮助。

英文:

I'm trying to understand the logic of the math.random or more specifically what is occurring and or why.

I understand essentially with the code below for example due to java being a 0 based language we start at 0 for indexing, etc.

the below code prints out a value between 0 and 10 inclusive.
11 is exclusive as understood.

int result = (int) (Math.random () * 11); 

My question is why for example if we were to get 0.99 * 10 then = 10.99
Why does the number not round up to 11?

Is this simply by design java will always round down to 0? or am I missing a concept?

Thank you for all your help.

答案1

得分: 2

在评论中我提到过:
将其转换为int将导致向下取整。这意味着您的数字将始终被舍入为0,因此在转换为int后,10.99将变为10。

您还可以参考这个链接

英文:

As I mentioned in the comments:
Casting to an int will result in a floor. This means that your number will always get rounded to 0, so 10.99 will become 10 after casting to int.

You can look at this reference as well

huangapple
  • 本文由 发表于 2020年7月22日 14:56:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63028543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定