java Math的问题

来源:百度知道 编辑:UC知道 时间:2024/06/04 04:56:18
代码如下:
public class CH11_01 {
public static void main(String args[]){
double a =Math.random();
System.out.println("默认的随机数类型 a ="+a);
System.out.println();
int[] num = new int[7];
System.out.println("自己设置大乐透号码产生器");
for(int i=0;i<num.length;i++){
num[i]= (int)(Math.random()*49+1);
System.out.print(num[i]+" ");
}
System.out.println("\n恭喜中了头奖2亿!!");
}

}

默认的随机数类型 a =0.06570103319167198

自己设置大乐透号码产生器
24 25 24 35 25 34 37

总是有重复的,怎样然他不重复呢

测试结果:
默认的随机数类型 a =0.3417964999475429

自己设置大乐透号码产生器
摇号失败:再次摇到 20 号码,重新摇号!
20 32 26 16 31 18 29
恭喜中了头奖2亿!!

import java.util.*;

public class CH11_01 {
public static void main(String args[]) {
double a = Math.random();
System.out.println("默认的随机数类型 a =" + a);
System.out.println();
int[] num = new int[7];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
System.out.println("自己设置大乐透号码产生器");
int h = 0;
int temp = -1;
while (h != num.length) {
temp = (int) (Math.random() * 49 + 1);
if (map.get(temp) == null) {
num[h++] = temp;
map.put(temp, temp);
}else{
System.out.println("摇号失败:再次摇到 " + temp + " 号码,重新摇号!");
}