2013-01-24 189 views
0

嘿,大家看看這個程序。srand函數返回相同的值

/* The craps game, KN king page 218 */ 

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

int roll_dice(void); 
bool play_game(void); 

int roll_dice(void) 
{ 
    int roll; 

    getchar(); 
    srand((unsigned) time(NULL)); 

    roll = rand() % 13; 

    if(roll == 0) 
    roll = roll + 1; 

    return roll; 
} 

bool play_game() 
{ 
    int sum = 0, wins = 0, loss = 0, point; 

    sum = roll_dice(); 

    printf("You rolled: %d", sum); 

    if(sum == 7 || sum == 11) 
    { 
     printf("\nYou won!\n"); 
     return true; 
    } 

    if(sum == 2 || sum == 3 || sum == 12) 
    { 
     printf("\nYou lost!!"); 
     return false; 
    } 

    point = sum; 

    printf("\n\nYour point is: %d", point); 

    do 
    { 
     sum = roll_dice(); 
     printf("\nYou rolled: %d", sum); 

    }while(sum != point); 

    if(sum == point) 
    { 
     printf("\nYou won!!!"); 
     return true; 
    } 

} 

int main() 
{ 
    char c, wins = 0, losses = 0; 
    bool check; 

    do 
    { 
     check = play_game(); 

     if(check == true) 
      wins++; 

     else if(check == false) 
      losses++; 

     printf("\nPlay Again? "); 
     scanf("%c", &c); 

    }while(c == 'Y' || c == 'y'); 

    printf("\nWins: %d  Losses: %d", wins, losses); 

    return 0; 
} 

srand函數不斷返回,相同的值3或4次,y是那個嗎?

我每次當我擲骰子時需要不同的值,複製代碼並運行它,看看我的意思

+1

我不知道這對你的家庭作業是否重要,但即使解決了問題後,請記住'roll = rand()%13;'將返回0和12包括在內。如果你應該模擬兩個六面骰子,那麼0或1的卷不好。而修正這個表達式導致2到12的值也可能不夠好,因爲來自兩個骰子的結果具有不均勻的分佈。 –

+0

@MichaelBurr:對。它應該是'(rand()%6)+(rand()%6)+ 2;'。 –

+0

@MichaelBurr一個很好的解決方案是隻需調用(rand()%6 + 1)兩次,然後添加那些實際上可以模擬雙骰子滾動 – RoneRackal

回答

8

srand()函數是設定種子的rand()函數的函數。你在這裏做的是在你調用每個rand()之前將當前時間設置爲當前時間,如果調用的足夠快,它會得到相同的值(因爲它將重置爲相同的種子,如果足夠快,同一時間值)。

你會想要做的是調用函數srand()一次,在程序啓動時(在你的main()函數的開始)

然後調用rand()你想有一個隨機數每一次,就像你現在正在做的一樣,但是不要每次都調用srand()。

+0

我同意,我得到了正確的輸出。非常感謝。我想早些時候說,但我的互聯網連接搞砸了。 – user1971996

+0

@ user1971996沒問題:D – RoneRackal