java模拟扔硬币的结果

来源:互联网 发布:windows10数据库 编辑:程序博客网 时间:2024/05/16 12:25
这里只模拟抛一枚硬币,即只有两种结果:正面(1)和反面(0)。


[java] view plain copy
  1. import java.util.Random;  
  2.   
  3.   
  4. /** 
  5.  * 模拟扔硬币的结果 
  6.  * @author  2017-5-15 
  7.  * 
  8.  */  
  9. public class Practice3_7 {  
  10.   public static void main(String[] args) {  
  11.     //方法一,随机取0,1  
  12.     Random rand=new Random();  
  13.     int a=rand.nextInt(2);  
  14.     System.out.println("a=="+a);  
  15.     if(a==0){  
  16.       System.out.println("反面");  
  17.     }else{  
  18.       System.out.println("正面");  
  19.     }  
  20.   
  21.     //方法二,随机选取大于等于 0.0 且小于 1.0 的伪随机 double 值  
  22.     double b=Math.random();  
  23.     System.out.println("b=="+b);  
  24.     if(b<0.5){  
  25.       System.out.println("反面");  
  26.     }else{  
  27.       System.out.println("正面");  
  28.     }  
  29.   }  
  30. }  


输出结果:

a==1
正面
b==0.8888502606423436

正面



转载来自:http://blog.csdn.net/jing7012796/article/details/72123318

原创粉丝点击