类型转换Math.random? [英] Type Casting Math.random?
问题描述
浏览了本网站上的问题,找不到关于将Math.random()
方法从double转换为int的类型的答案.
我的问题是,为什么Math.random
只返回不带括号的0,而当它包含在括号中时却返回随机数?
代码的第一部分返回0:
Had a look around the questions on this site and could not quite find the answer I was looking for about type casting the Math.random()
method from double to int.
My question is, why does Math.random
only return a 0 without parentheses whereas it returns random numbers when it is contained within the parentheses?
The first part of code returns 0:
int number;
number = (int) Math.random() * 10;
System.out.println("\nThe random number is " + number);
但是此代码有效:
int number;
number = (int) (Math.random() * 10);
System.out.println("\nThe random number is " + number);
应该指出的是,我在类型转换中看到了几段不同的代码,其中一些程序员似乎同时使用了两种转换方式.
It should be noted I have seen a few different pieces of code on typecasting whereby some programmers seem to use both ways of casting.
推荐答案
此代码:
number = (int) Math.random() * 10;
首先计算:
(int) Math.random()
由于Math.random()
返回一个从0到但不包括1的数字,如果将其强制转换为int,则将向下舍入为0.然后将10乘以0便得到0.
Since Math.random()
returns a number from 0 up to but not including 1, if you cast it to int, it will round down to 0. Then when you multiply 10 to 0 you get 0.
这篇关于类型转换Math.random?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!