【问题标题】:Expected result not achieved with java but yes with c#使用 java 未达到预期结果,但使用 c# 可以
【发布时间】:2011-05-31 11:52:08
【问题描述】:

我有一个程序旨在模拟一些概率问题(如果您有兴趣,可以将其变种为 monty hall 问题)。

代码在足够的迭代后预计会产生 50%,但在 java 中它总是达到 60%(即使在 1000000 次迭代之后),而在 C# 中它达到预期的 50% 是否有一些不同的东西我不知道java的Random可能吗?

代码如下:

import java.util.Random;

public class main {


    public static void main(String args[]) {
        Random random = new Random();

        int gamesPlayed = 0;
        int gamesWon = 0;

        for (long i = 0; i < 1000l; i++) {

            int originalPick = random.nextInt(3);
            switch (originalPick) {
            case (0): {
                // Prize is behind door 1 (0)
                // switching will always be available and will always loose
                gamesPlayed++;
            }
            case (1):
            case (2): {
                int hostPick = random.nextInt(2);
                if (hostPick == 0) {
                    // the host picked the prize and the game is not played
                } else {
                    // The host picked the goat we switch and we win
                    gamesWon++;
                    gamesPlayed++;
                }
            }
            }
        }

        System.out.print("you win "+ ((double)gamesWon / (double)gamesPlayed )* 100d+"% of games");//, gamesWon / gamesPlayed);
    }

}

【问题讨论】:

  • 使用调试器,您会看到缺少break; 子句。我建议你学习如何使用你的调试器。 (它通常在你的 IDE 中运行旁边)
  • 别担心,我知道如何使用调试器:)
  • @Jason 楼主为什么随机选择?主持人知道门后是什么,所以永远不会挑选奖品。
  • @Jason,我想你当时忘了使用它。 ;)
  • @Jason,随机工作正常。您的问题是关于正确使用 Random ,因此您的标题非常具有误导性。我建议改变它。

标签: c# java random


【解决方案1】:

至少,您忘记了以 break 语句结束每个 case 块。

所以对于这个:

switch (x)
{
case 0:
    // Code here will execute for x==0 only

case 1:
    // Code here will execute for x==1, *and* x==0, because there was no break statement
    break;

case 2:
    // Code here will execute for x==2 only, because the previous case block ended with a break
}

【讨论】:

  • 大声笑你是对的,我在 java 版本中忘记了这一点。谢谢
【解决方案2】:

您忘记在 case 语句的末尾添加换行符,因此 case (1) 继续到 case (3)。

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    相关资源
    最近更新 更多