C++ rand() 只在 1-10 之间生成 8

c++ rand() only generating 8 between 1-10

本文关键字:之间 1-10 只在 rand C++      更新时间:2023-10-16

我正在尝试生成一个介于 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;
}

您应该在rand()之前使用srand(time(nullptr))

在使用之前,您应该使用srand()来播种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 (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;
}