【问题标题】:Generating random numbers with a loop使用循环生成随机数
【发布时间】:2014-02-14 08:35:20
【问题描述】:

我在玩这个“随机数游戏”时遇到了麻烦。
我希望随机数仅在内部执行时保持其值,并在用户决定重试时更改。 我认为在循环外添加 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;
}

【问题讨论】:

  • 提示 - 什么改变了值?应该在内循环、外循环还是两个循环之外?

标签: c++ loops if-statement random srand


【解决方案1】:

想象一长串“伪随机”数字。有一个指向行中某个位置的指针,调用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。

【讨论】:

  • 我意识到我将 rand() 作为底部函数的静态函数,它不会让我的数字发生变化。
【解决方案2】:

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

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

unsigned int seed=time(NULL);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2016-09-11
    • 2021-04-30
    相关资源
    最近更新 更多