如何生成高于或低于之前生成的随机数的随机数?

How can I generate a random number which is, higher or lower than the random number generated before?

本文关键字:随机数 于之前 何生成 高于      更新时间:2023-10-16

/*我希望代码生成一个高于先前生成的随机整数(如果猜测较高),而不是增加 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_limitlow_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));

注意:使用正确的标题。

更新

根据您的评论,您可以使用额外的两个变量,例如:minguessmaxguess来缩小随机生成范围。 检查以下代码段:

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);