英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论