srand is too slow in C++ it return same number

旧城冷巷雨未停 提交于 2019-12-20 07:49:17

问题


I'm just trying to have simply RndInt(limit) function that will return random numbers with a limit as limit.

    cout << "Enter higher limit of random range:" ;
 cin >> limit;
 while(limit != 0)

{
//        RndInt(limit);
    cout << "Random number smaller than " << limit << " is " << RndInt(limit) << endl;
    cin.get();
    cin.get();
    cout << "Other random number smaller than " << limit << " is " << RndInt(limit) << endl;
    cin.get();
    cin.get();
    cout << "There is " << RndInt(limit) << " ways I love you" <<endl ;
    cout << "Enter higher limit of random range:" ;
    cin >> limit;
}
return 0;
}

int RndInt(int limit)
{
srand(time(&base));
int rndnumber;
rndnumber=rand()%limit;
base+=100;
return rndnumber;
}

I'm having problem to make RndInt subsequent calls display different integer. When I debug its fine subsequent calls to RndInt(limit) give different value. But when I try to run it without cin.get() for pause I get same numbers in all three calls. I figured out that problem is that seed is in the same second.

My question is how to make calls to RndInt return different values without pause. What to do to srand function ?


回答1:


Do not call srand() every time you want a random number. Call srand() once at the start of your program, and then call rand() for each number.



来源:https://stackoverflow.com/questions/11623594/srand-is-too-slow-in-c-it-return-same-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!