Java随机数使用范例,扔硬币的概率统计
转自:http://blog.csdn.net/u010673067/
方法2
public class coin{ public static void main(String args[]){ int n = 0; int m = 0; int len = 1000; int str[] = new int[len]; for(int i = 0 ; i < len ; i ++){ str[i] = ( int )(Math.random()*2); if(str[i] == 1 ){ n = n + 1; }else{ m = m + 1; } } System.out.println("正面朝上的次数:"+n); System.out.println("反面朝上的次数:"+m); } }
方法2
方法二: package org.lxh.demo.coin; import java.util.Random; public class coin{ public static void main(String args[]){ int n = 0; int m = 0; int len = 1000; int str[] = new int[1000]; //创建一千个的数组 Random rad = new Random(); for(int i = 0 ; i < len ; i ++){ str[i] = rad.nextInt(2); //为一千个的数组赋值 if(str[i] == 1 ){ n = n + 1; }else{ m = m + 1; } } System.out.println("正面朝上的次数:"+n); System.out.println("反面朝上的次数:"+m); } }