如何生成高于或低于之前生成的随机数的随机数?
How can I generate a random number which is, higher or lower than the random number generated before?
/*我希望代码生成一个高于先前生成的随机整数(如果猜测较高),而不是增加 1 或减少 for 循环中的随机数,如果猜测较高,则生成一个小于先前生成的随机整数。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main(){
int counter = 0;
unsigned int guess;
srand(time(NULL));
unsigned int random_number = (rand() % 100)+ 1;
std::string higher = "higher";
std::string lower = "lower";
std::string value = "";
cout << "Please enter a number between 1 and 100, so the computer can guess it!" << endl;
cin >> guess;
cout << random_number << endl;
while (guess != random_number)
{
cout << "Is it a lower or higher value?" << endl;
cin >> value;
if (value == higher)
{
for(int i = 1; i< 2; i++)
{
random_number = random_number + 1;
cout << random_number << endl;
}
}
else if (value == lower)
{
for(int i =1; i < 2; i++)
{
random_number = random_number - 1;
cout << random_number << endl;
}
}
}
cout << "This PC is fabulous" << endl;
return 0;
}
您只需要使用新限制调用随机。
为了使事情变得更容易,让我们编写一个函数,该函数在我们指定的任意两个限制之间生成整数,例如low_limit
和low_limit
.
int random(int low_limit, int up_limit){
return rand() % ((up_limit - low_limit) + 1) + low_limit;
}
现在通过调用函数生成第一个数字,并将结果保存到temp
变量中。
temp = random (0, 100);
现在,根据用户输入,您可以使用temp
像这样调用random
:
if (value == higher)
temp = random (temp, 100);
else if (value == lower)
temp = random (0, temp);
对于每次运行的不同随机数,您可以将srand
函数与参数一起使用,该参数每次都可以像系统时间一样给出不同的种子。
srand(time(NULL));
注意:使用正确的标题。
更新
根据您的评论,您可以使用额外的两个变量,例如:minguess
和maxguess
来缩小随机生成范围。 检查以下代码段:
srand(time(NULL));
int choice, minguess = 0, maxguess = 100, current;
do{
choice = 0;
current = random(minguess,maxguess);
cout << "n My guess is: " << current << "n";
while (choice < 1 || choice > 3){
cout << "n Enter you choice: n";
cout << " 1- higher. n";
cout << " 2- lower. n";
cout << " 3- quit. nn";
cin >> choice;
}
if (choice == 1)
minguess = current;
else if (choice == 2)
maxguess = current;
} while (choice != 3);
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 整数不会重复超过随机数
- 如何确保C++函数在定义之前声明(如override关键字)
- 为什么在定义函数之前先声明它
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- c++r值引用应用于函数指针
- 如果编译的源代码是特定于它编译的硬件的,我们如何分发它
- 如何仅使用对象名称打印特定于对象的成员
- 相当于LocaleMatcher的ICU4C
- 等<thing>效于char32_t
- 类似于strcat()的函数出现问题
- 如何生成高于或低于之前生成的随机数的随机数?
- 如何根据用户输入"weighted"随机数生成,使某些数字优先于其他数字?
- 在插入之前使用 lower_bound 搜索地图的好处.相当于ptr_map?
- 为什么我的简单C++项目在我可以看到之前就终止于日食?我如何让它停止
- 为什么在使用rand生成随机数之前需要调用srand
- 应用于单词数组的随机数范围
- 在失去随机性之前,std::uniform_real_distribution可以生成多少个随机数
- visual studio 2010 -浮点/双精度随机数的小范围,适用于整型(c++, VS2010)