博客 / 詳情

返回

擲骰子游戲

題目:
骰子是一個有六個面的正方體,每個面分別印有1〜6之間的小圓點代表點數。假設這個遊戲的規則是:兩個人輪流擲骰子6次,並將每次投擲的點數累加起來。點數多者獲勝;點數相同則為平局。

思路
由於骰子六面概率平均,所以這裏用隨機數函數計算兩個,最後統計兩者的勝率即可
隨機數含義及運用

完整代碼如下:

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

int main()
{
    int d1, d2, c1, c2;
    int i = 0;
    c1 = c2 = 0;
    srand((unsigned)time(NULL));
    rand();
    d1 = d2 = 0;

    for (i = 1; i <= 10; i++)
    {


        d1 = d1 + rand() % 6 + 1;
        d2 = d2 + rand() % 6 + 1;

    }
    if (d1 > d2)
        c1++;
    else if (d1 < d2)
        c2++;
    if (c1 > c2)  /*輸出最終獲勝者信息*/
        printf("\nThe first win.\n");
    else
        if (c1 < c2)
            printf("\nThe second win.\n");
        else
            printf("They tie.\n");

    return 0;
}

輸出結果(結果隨機):
圖片.png

user avatar luguolangren 頭像 l_twilight_ximu 頭像
2 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.