C++ c++;rand()仅在1-10之间生成8

C++ c++;rand()仅在1-10之间生成8,c++,random,C++,Random,我试图生成一个介于1-10之间的随机数,然后让我的switch语句输出一周中的任意一天,但我无法让它输出除8之外的任何其他数字 #include <iostream> #include <cstdlib> using namespace std; int main() { int a = rand() % 10 + 1; cout << a << endl; if (a != 4) { cout <<

我试图生成一个介于1-10之间的随机数,然后让我的switch语句输出一周中的任意一天,但我无法让它输出除8之外的任何其他数字

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    int a = rand() % 10 + 1;
    cout << a << endl;
    if (a != 4)
    { cout << endl << "a is less than 4" << endl;}
    else
    { cout << endl << "a is greater than or equal to 4";}


    return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
int a=rand()%10+1;
cout您应该在
rand()
之前使用
srand(time(nullptr))

您应该在使用它之前使用它来设置
rand()

rand()
的输出取决于所使用的种子。每次运行程序时都使用相同的默认种子,每次都会产生相同的输出

播种rand的一种常见方法是随时间:

#include <cstdlib>
#include <ctime>

int main() {

    // Use current time as seed for random generator
    srand(time(0));

    // Do stuff with rand()

}
#包括
#包括
int main(){
//使用当前时间作为随机生成器的种子
srand(时间(0));
//与兰德(rand)合作
}

这样,每次运行程序时都会得到不同的结果,因为每次执行程序的时间都不同。

初始化随机种子并继续

int main()
{
    srand (time(NULL));

    int a = rand() % 10 + 1;

    cout << a << endl;
    if (a < 4)
    {
        cout << endl << "a is less than 4" << endl;
    }
    else
    {
        cout << endl << "a is greater than or equal to 4";}
        return 0;
    }
intmain()
{
srand(时间(空));
int a=rand()%10+1;

无法在教科书中查找srand。更好的是,查找
标题中声明的功能。a!=4并不意味着“a小于4”。您需要运行srand()来为rand()使用的伪随机数生成器种子。可能重复@HarrisonStott如果您的问题得到了充分的回答,您可以通过单击您发现最有用的答案旁边的复选标记将其标记为已解决。请注意,如果此程序在两次运行之间的时间非常短,则由于
time()的粒度,它仍然可以在两次运行时产生相同的值
function。现实世界中的程序需要足够长的时间才能运行,这样你就不会碰到这个问题,但像这样的简单测试程序可能会被愚弄。投票表决。