C++ 在c+中生成介于1和9之间的随机数+;

C++ 在c+中生成介于1和9之间的随机数+;,c++,C++,我需要添加什么,以便它不会连续选择数字8,而是选择数字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." &l

我需要添加什么,以便它不会连续选择数字8,而是选择数字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;
}
intmain()
{
int iRand=(rand()%9+1);
if(iRand==1)
{

不能您需要初始化您的第一个

#包括/*srand,兰德*/
#包括/*时间*/
srand(时间(空));
伪随机数生成器,如
rand()
,实际上并不是完全随机的。相反,这些数字是由生成器的初始状态(称为种子)决定的。您的程序(现在的程序)在每次执行时都会有相同的种子,因此每次执行时的随机数都是相同的

srand()
用于拯救——它允许您指定种子

如果要指定一个常量种子(如
srand(2)
)因此,为了保证每次程序执行时都有不同的结果,我们可以用当前时间初始化随机数生成器——因此,只要你不在时间中旅行,就永远不会得到完全相同的数字序列


(注意:在现实世界的应用程序中,这可能不太好,因为有人可能会通过(例如)手动将系统时钟重置为不同的时间来重复过去的结果。这会从赌场偷钱。)

请查看
srand()
函数。如果您的编译器支持C++11,那么最好放弃
rand()
并使用新的随机工具。这个问题很可能也是重复的。看起来你需要注意括号()。试试
(rand()%8)+1
。冥王星不再是行星了…;)冥王星仍然想成为行星,我很高兴你没有伤害冥王星的感情。
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

srand (time(NULL));