当前位置: 代码迷 >> Java相关 >> 编写一个程序模拟扔硬币的结果
  详细解决方案

编写一个程序模拟扔硬币的结果

热度:377   发布时间:2010-01-28 21:57:25.0
编写一个程序模拟扔硬币的结果
import java.util.Random;

public class Coin {

    public static void main(String[] args) {
        Random rand = new Random();
        int x = 0;
        int y = 0;
        for(int j = 0 ; j < 1000000; j++) {
            int i = rand.nextInt(2);
            //System.out.println(i);
            if (i==1) {
                x++;
            } else {
                y++;
            }
        }
        System.out.println("x="+x);
        System.out.println("y="+y);
        System.out.println((float)x/y);
        

    }

}
搜索更多相关的解决方案: 模拟  编写  结果  硬币  

----------------解决方案--------------------------------------------------------
随机数字
----------------解决方案--------------------------------------------------------
嗯,支持一个
----------------解决方案--------------------------------------------------------
呵呵 正巧我今天下午也做了一个类似的程序 这个是为了一个小游戏做的TEST 请高手指教

import java.util.Random;   
import java.util.*;
public class Game     
{
    public static void main(String[] args)   
    {      
        {   
            int a, b = 0;
            Scanner input = new Scanner(System.in);
            System.out.println("Please enter the scope of the coins: ");
            a=input.nextInt();
//            for(int i=0; i<1; ++i)
            b = new Random().nextInt(a)+30;
            System.out.println("\nThe number of coins is " + b);
        }   
            
            Scanner input = new Scanner(System.in);
            System.out.println("\nPlease choose the side of the coin:(0 or 1) ");
            int Num = input.nextInt();
            System.out.println("\nThe side you chose is " + Num);
            int RandomNum = new Random().nextInt(2);
            System.out.print("\nThe side of coin is " + RandomNum);
            if (Num == RandomNum)
            {
                System.out.print("\n\nCongratulations! Please take the coins:");
            }
            else
            {
                System.out.print("\n\nSorry, Wrong side, Please wait...");
            }
    }
        
}
----------------解决方案--------------------------------------------------------
  相关解决方案