[英]Math.random not properly working in the code
package arrays;
import java.util.Scanner;
public class Raffle {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter the number of partcipants ");
int no=scan.nextInt();
String participants[]=new String[no];
System.out.println("Please enter their names and check out the random winner");
for(int i=0;i<no;i++) {
participants[i]=scan.next();
}
int rand=(int)Math.random()*no;
System.out.println(rand);
System.out.println("The winner of the raffle is "+participants[rand]);
}
}
我使用了Math.random()
但在运行过程中看到总是0索引位置给出结果,而不是随机值。 有什么建议么? 我正在食蚀性氧气。
您将Math.random()
的结果强制转换为int
然后再乘以no
,结果为0
,因为Math.random() < 1.0
。
更改
int rand=(int)Math.random()*no;
至
int rand=(int)(Math.random()*no);
在0.0(含)和1.0(不含)之间转换一个双精度值将始终舍入为零。 在将Math.random()值转换为int值之前,应先将其与某个因子相乘,以得到介于零(含)和乘法因子(不含)之间的值。 另一种可能的解决方案是使用java.util.Random的nextInt()方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.