rand()在编译时生成相同的数字 [英] rand() generating same number upon compilation

查看:116
本文介绍了rand()在编译时生成相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


我一直在学习如何使用rand()函数,我在C ++中写了一个小猜测游戏,如下所示,但问题是,无论如何很多时候我编译程序生成的数字是一样的 - > 41

  #include< iostream> 
#include< cstdlib>
#include< conio.h>
using namespace std;

int main()
{
int x = rand()%100;
int y = 0;
cout<< Ghiceste numarul! << endl;
cin>> y;

while(y!= x){

if(y> x){
cout< Numarul tau este prea mare!Incearca un numar mai mic! << endl;
cin>> y;
}

if(y< x){
cout< Numarul tau este prea mic! << endl;
cin>> y;
}

if(y == x){
cout< FELICITARI,AI GHICIT NUMARUL!\\\
;
return 0;
}
}
}

max的rand(),它的确改变了,只要我把它< 41。



有什么想法吗?我没有一个线索为什么会发生这种情况。我使用CodeBlocks IDE并尝试重建(CTRL + F11)

解决方案

尝试添加

  srand(time(0));  main 开头处的


Possible Duplicate:
What's the Right Way to use the rand() Function in C++?

I've been learning how to use the rand() function and I wrote a small guessing game in C++ as seen bellow, but the problem is, no matter how many times I compile the programs the generated number is the same -> 41

#include <iostream>
#include <cstdlib>
#include <conio.h>
using namespace std;

int main()
{
    int x = rand()%100;
    int y=0;
    cout << "Ghiceste numarul!" << endl;
    cin >> y;

    while(y != x) {

         if(y > x) {
            cout << "Numarul tau este prea mare! Incearca un numar mai mic!" << endl;
            cin >> y;
          }

             if(y < x) {
                 cout << "Numarul tau este prea mic!" << endl;
                 cin >> y;
               }

      if (y == x) {
      cout << "FELICITARI, AI GHICIT NUMARUL!\n";
      return 0;
      }
    }
}

I also tried to change the max value of rand() and it did change as long as I put it < 41.

Any ideas? I don't have a clue as to why this is happening. I am using CodeBlocks IDE and I tried rebuilding (CTRL+F11)

解决方案

Try adding

srand(time(0));

at the beginning of main.

这篇关于rand()在编译时生成相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆