C++中rand()%100在每次执行时所给的随机数都是41,如何每次执行得到不同的随机数?

如题所述

第1个回答  2013-06-01
#include <iostream>#include <ctime>#include <cstdlib>
using namespace std;
void main()
{ srand(static_cast<unsigned int>(time(NULL))); // 初始化随机种子, 这样就不会都出现41了
int num=rand()%100;
int guess;
int i=0;
cout<<"Guess a number (1-100):"<<endl;
while(1)
{
cin>>guess;
i++;
if(guess==num)
{
cout<<"You are right, guess"<<i<<"times."<<endl;
break;
}
else if((guess>num)&&(i<10))
cout<<"Guess too big, try again:";
else if((guess<num)&&(i<10))
cout<<"Guess too small, try again:";
else
{
cout<<"Sorry, game over!"<<endl;
break;
}
}
}本回答被网友采纳
第2个回答  2013-06-01
在调用rand前 调用一下srand(time(0));
相似回答