Java math.random,只生成一个0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19162331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
math.random, only generating a 0?
提问by Christopher Baldwin
The following code is only producing a 0 ;-;
以下代码仅产生 0 ;-;
What am I doing wrong?
我究竟做错了什么?
public class RockPaperSci {
public static void main(String[] args) {
//Rock 1
//Paper 2
//Scissors 3
int croll =1+(int)Math.random()*3-1;
System.out.println(croll);
}
}
Edit, Another Poster suggested something that fixed it. int croll = 1 + (int) (Math.random() * 4 - 1);
编辑,另一张海报建议了一些修复它的东西。int croll = 1 + (int) (Math.random() * 4 - 1);
Thanks, everyone!
谢谢大家!
采纳答案by Sotirios Delimanolis
You are using Math.random()
which states
您正在使用Math.random()
哪些州
Returns a
double
value with a positive sign, greater than or equal to0.0
and less than1.0
.
返回一个
double
带正号的值,大于或等于0.0
并小于1.0
。
You are casting the result to an int
, which returns the integer part of the value, thus 0
.
您将结果强制转换为int
,它返回值的整数部分,因此0
。
Then 1 + 0 - 1 = 0
.
然后1 + 0 - 1 = 0
。
Consider using java.util.Random
考虑使用 java.util.Random
Random rand = new Random();
System.out.println(rand.nextInt(3) + 1);
回答by Rohit Jain
Math.random()
generates double values between range - [0.0, 1.0)
. And then you have typecasted the result to an int
:
Math.random()
在范围 - 之间生成双精度值[0.0, 1.0)
。然后您将结果类型转换为int
:
(int)Math.random() // this will always be `0`
And then multiply by 3
is 0
. So, your expression is really:
然后乘以3
is 0
。所以,你的表达真的是:
1 + 0 - 1
I guess you want to put parenthesis like this:
我猜你想像这样放置括号:
1 + (int)(Math.random() * 3)
Having said that, you should really use Random#nextInt(int)
method if you want to generate integer values in some range. It is more efficient than using Math#random()
.
话虽如此,Random#nextInt(int)
如果你想在某个范围内生成整数值,你真的应该使用方法。它比使用更有效Math#random()
。
You can use it like this:
你可以这样使用它:
Random rand = new Random();
int croll = 1 + rand.nextInt(3);
See also:
也可以看看:
回答by Prabhakaran Ramaswamy
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
返回带正号的双精度值,大于或等于 0.0 且小于 1.0。返回值是伪随机选择的,具有该范围内的(近似)均匀分布。
int croll =1+(int)Math.random()*3-1;
eg
例如
int croll =1+0*-1;
System.out.println(croll); // will print always 0
回答by Suresh Atta
All our mates explained you reasons of unexpected output you got.
我们所有的伙伴都向您解释了意外输出的原因。
Assuming you want generate a random croll
假设你想生成一个随机 croll
Consider Random
for resolution
考虑Random
解决
Random rand= new Random();
double croll = 1 + rand.nextInt() * 3 - 1;
System.out.println(croll);