-
Math.random();
double ans=Math.random()//随机返回[0,1)之间小数
double ans2=Math.random()*8//随机返回[0,8)之间小数
int ans3=int(Math.random()*k)//[0,k-1]随机整数
//以上方法[0,x)x出现的概率都是x
//把数出现概率由x调整为x平方
return Math.max(Math.random(),Math.randomn())
-
题目:有一个能随机返回1-5随机数的函数改,得到1-7的随机数
-
首先明确目标函数和条件函数
-
通过条件函数得到0.1发生器:得到1,2返回0;得到4,5返回1;得到3重新生成
-
如何通过0,1生成函数得到目标函数:使用三个0,1生成函数(二进制位:000-111),得到0-7
-
改成0-6再+1
-
public class test1 {
//设计一个返回1-5随机数的函数
public static int f1(){
return (int)(Math.random()*5)+1;
}
//返回随机数0和1【注意不是0-1,所以不能直接得到1-7】
public static int f2(){
int i ;
do{
i=f1();
}while(i==3);
if(i<3){
return 0;