欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java:,

来源: javaer 分享于  点击 39778 次 点评:141

java:,


豆机,也叫梅花瓶或高尔顿机,它是用来做统计实验的设备,使用英国科学家瑟弗兰克斯高尔顿的名字命名的。它是一个三角形状的均匀放置钉子的直立板子。如下图所示:



球都是从板子口落下,每当碰到钉子,它就有50%的机会落向左边或右边。在板子底部的槽子中都会积累一些球。编写程序模拟豆机。程序提示用户输入球的个数以及机器的槽数。打印每个球的路径模拟它的下落,并显示最终每个槽子中球的数目。






完整代码(该方法接近50%,但有理论的可能性达不到,随机数为0的话,在进行一次产生随机数)


import java.util.Scanner;

public class Exercise6_21 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the numbers of balls to drop:");
        int key = input.nextInt();
        System.out.print("Enter the numbers of slots in the bean machine:");
        int hole = input.nextInt();
        char[] judgement = new char[hole - 1];
        int[] slots = new int[hole];

        for (int i = 0; i < key; i++) {
            int sum = 0;
            for (int j = 0; j < hole - 1; j++) {
                double x = Math.random() * 2.0 - 1;
                if (x < 0) judgement[j] = 'L';
                else if (x > 0) judgement[j] = 'R';
                else {
                    double y = Math.random() * 2.0 - 1;
                    if (y < 0) judgement[j] = 'L';
                    else if (y > 0) judgement[j] = 'R';
                }
            }

            for (int n = 0; n < hole - 1; n++) {

                if (judgement[n] == 'R')
                {
                    sum++;
                }

            }
            slots[sum]++;


            System.out.println(judgement);

        }

        int numberOfSlots = max(slots);

        for (int o = 0; o < numberOfSlots; o++) {
            for (int j = 0; j < hole; j++) {
                if (slots[j] == numberOfSlots - o) {
                    System.out.print('0');
                    slots[j]--;
                } else
                    System.out.print(' ');
                }
                System.out.println();
            }


        }

    public static int max(int[]num){
        int maxNum = 0;
        for(int i = 0;i < num.length;i++){
            if(num[i] > maxNum)
                maxNum = num[i];
        }
        return maxNum;
    }

}


相关文章

    暂无相关文章
相关栏目:

用户点评