C++ rand() 只在 1-10 之间生成 8
c++ rand() only generating 8 between 1-10
我正在尝试生成一个介于 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;
}
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- #define DATA 10 和 # (如果定义了 DATA)之间的差异
- C++ rand() 只在 1-10 之间生成 8
- 程序查找 1 到 10^7 之间的素数之和
- 创建一个带有限制的数字数据类型,一个介于 -10 和 10 之间的整数
- 使用 C++ 的 1 到 10 之间的随机数
- 我们应该使用哪种数据类型来输入一个介于 0<= 数字 <= 10^18 之间的数字
- C字符串,如何确定字符长度是否在6到10之间
- 返回括号 (10, 20, 30, 40) 之间的值列表
- C++ 创建一个介于 0.1 和 10 之间的随机小数
- 10-200之间的素数只使用while循环C++
- 在10^10到10^11之间的数字的数据类型应该是什么
- 从基数10转换为2到36之间的任意基数
- 当m和n在10^10范围内相当大时,使用埃拉托色尼筛法打印m和n之间的素数
- 如何生成1到10^6之间的随机数
- Visual Studio 10 和 GCC 4.5 之间的哪个编译器在运算符重载和参数相关查找方面是正确的
- 在Visual C++10中在项目之间共享文件
- solaris 10 gcc 4.8.2上的-lpthread和-phreads之间有什么区别
- GCC 和 MSVC 之间的数字差异10
- 生成0到10之间的随机数