C++ 用循环生成随机数

C++ 用循环生成随机数,c++,loops,if-statement,random,srand,C++,Loops,If Statement,Random,Srand,我玩这个“随机数游戏”有问题。 我希望随机数仅在内部do时保持其值,并在用户决定重试时更改。 我以为在循环之外添加srand会每次都改变值,但事实似乎并非如此 //Libraries #include <ctime> #include <cstdlib> #include <iostream> using namespace std; //Global Constants //Function Prototypes int rnd();//random

我玩这个“随机数游戏”有问题。
我希望随机数仅在内部do时保持其值,并在用户决定重试时更改。 我以为在循环之外添加
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;
}
//库
#包括
#包括
#包括
使用名称空间std;
//全局常数
//功能原型
int rnd()//随机数函数
//行刑从这里开始
int main(int argc,char*argv[]){
//声明变量
无符号整数种子=时间(0);
int n;
字符a;
//设置随机数种子
srand(种子);
做{
做{
//提示用户;
cout想象一长行“伪随机”数字。有一个指向行中某个位置的指针,调用
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  


提示-是什么改变了值?是在内循环、外循环还是在两个循环之外?我意识到我在底部有一个静态函数rand(),它不允许我的数字改变。
unsigned int seed=time(NULL);