我需要添加什麼,以便它不會連續選擇數字8而是數字1到9中的任何一個?函數srand?在C++中生成1到9之間的隨機數
int main()
{
int iRand = (rand() % 9+1);
if (iRand==1)
{
cout << "The planet of the day is Mercury!" <<endl;
cout << "Mercury is the closest planet to the sun." <<endl;
}
else if (iRand==2)
{
cout << "The planet of the day is Venus!" <<endl;
cout << "Venus is the hottest planet in our solar system." <<endl;
}
// .... 3..4..5..6..7..8
else
{
cout << "The planet of the day is Pluto!" <<endl;
}
return 0;
}
看看'srand()'函數。 –
如果你的編譯器支持C++ 11,那麼溝通'rand()'並使用新的隨機工具可能是明智的。這個問題很可能也是重複的。 – goji
看起來你需要看你的括號()。試試'(rand()%8)+ 1'。 – 2013-10-08 03:52:14