簡體   English   中英

循環生成隨機數

[英]Generating random numbers with a loop

我在使用“隨機數游戲”時遇到了麻煩。
我希望隨機數僅在內部執行時保持其值,並在用戶決定重試時更改它。 我以為在循環之外添加srand每次都會更改值,但事實並非如此。

//Libraries
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;

//Global Constants


//Function Prototypes
int rnd();//random number function

//Execution Begins Here
int main(int argc, char *argv[]){
    //Declare Variables
    unsigned int seed=time(0);
    int n;
    char a;

    //set the random number seed
    srand(seed);
    do{
        do{
           //Prompt user;
           cout<<"*** Random Number Guessing Game *** \n"
               <<"    Guess a number between 1-10,   \n"
               <<"     Enter your number below!     \n";
           cin>>n;
           //process
             if(n<rnd()){
             cout<<" Too low, try again.\n";

             }else if(n>rnd()){
             cout<<" Too high, try again.\n";

             }else if(n==rnd()){
             cout<<rnd()<<" Congradulations you win!.\n";
             }
        }while(n!=rnd());
        cout<<"try again? (y/n)\n";
        cin>>a;
    }while(a=='y' || a=='Y');
    system("PAUSE");
    return EXIT_SUCCESS;
}
int rnd(){
    static int random=rand()%10+1;
    return random;
}

想象一排“偽隨機”數字。 行中有一個指向rnd()的指針,調用rnd()打印出所指向的數字,並將指針移至下一個數字。 rnd()的下一次調用執行相同的操作。 除非兩個相同的數字碰巧彼此相鄰(這種情況可能發生但不太可能),否則您將為兩次不同的rand調用獲得兩個不同的數字。 當您調用srand您基本上將指針設置為該行上的已知點,因此對rnd()調用將返回其之前所做的操作。

在圖片中:

srand(0)
... 1 9 3 4 9 7 ...
  ^  (srand puts the pointer to 9.)
a call to rand returns 9 and updates the pointer:
... 1 9 3 4 9 7 ...
        ^ 
the next call to rnd() will return 3.

If you call srand(0) again it'll be 
... 1 9 3 4 9 7 ...
      ^  
and a call to rnd() will return 9 again.

如果要保留相同的“隨機”數字,請一次調用rnd並保存該值,直到再次需要它為止,而不是每次都調用rnd。

使用srand(time(NULL)); 代替srand(seed); 或者你可以改變

unsigned int seed=time(0);  
                       ^ You are seeding same value every time  

unsigned int seed=time(NULL);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM