1

我编写了这个程序,该程序将一对骰子掷了 20000 次。规则是:

  • 如果掷出 7 或 11,则玩家获胜
  • 如果掷出 2、3 或 12,则玩家输。
  • 如果以上都没有滚动,则存储总和并再次滚动骰子

二轮规则:

  • 如果掷出 7,则玩家获胜
  • 如果掷出与之前相同的总和,则玩家输
  • 如果不是,则玩家再次滚动,直到满足这两个条件中的任何一个。

最后,它会计算赢得比赛的百分比。我的问题是,根据同事的说法,我应该获得 39%-60% 左右的游戏获胜率,但每次运行程序时,我都会获得 20% 左右,我不明白为什么。难道我做错了什么?有人能帮助我吗?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main()
{   
int dieOne, dieTwo, keyValue, value, wins = 0, firstWins = 0, subWins = 0, loss = 0, count=0;
double percentWin, percentFirstWins, percentSubWins;
srand(time(NULL));

do{
dieOne = rand() % 6 + 1;
dieTwo = rand() % 6 + 1;
value = dieOne + dieTwo;
count++;


if (value==7||value==11) {
    firstWins++;
    wins++;
}

else if (value== 2||value==3||value==12) {
    loss++;
}

else {
    do{ 
    keyValue = value;

    dieOne = rand() % 6 + 1;
    dieTwo = rand() % 6 + 1;
    value = dieOne + dieTwo;
    count++;

    if (value==7) {
    subWins++;
    wins++;
    }

    else if (value = keyValue) { 
        loss++;
    }

    } while ( value != 7 && value != keyValue );
}
} while (count <= 20000);

    percentWin = (double) wins/count * 100;
    percentFirstWins = (double) firstWins/count * 100;
    percentSubWins = (double) subWins/count * 100;
    printf("You won %.1lf percent of your games! \nYou won %.1lf percent of games on the first roll.\nYou won %.1lf percent of games on the second roll.\n", percentWin, percentFirstWins, percentSubWins );

    system("pause");
}

掷出 7 有 6 种可能的方式,掷出 11 有两种可能的方式
。在第一次掷骰时共有 8 种可能的获胜方式。
掷骰子有 36 (6^2) 种可能的方式。这意味着您有 36 分之 8 的机会在第一次掷骰时获胜,或大约 22% 的时间获胜。

此外,我们有 2 种可能的方式来掷 2,2 种可能的方式来掷 3,以及 2 种可能的方式来掷 12。所以这意味着在第一次失败时有六分之一的机会 (6/36)滚动,或大约 17% 的时间。

所以剩下的61%的胜负都要来自第二卷。无论如何,我的程序产生了非常高的连败,而我同事的程序似乎产生了 40-60% 的总胜率。我哪里错了?

4

1 回答 1

1

This may be what's causing your problem:

else if (value = keyValue) {

You're assigning, rather than comparing. This will always evaluate to true, thus artificially inflating your losses. You should be using == here instead of =.

Also, for rolls that are neither a win nor a loss, you're not incrementing either the wins or the loss counter for either of those, but you are adding to count. So you're going to end up with a situation where wins + loss != count. When you calculate the win percentage, try calculating it as wins / (loss + wins).

于 2012-09-24T23:11:56.017 回答