/ *而不是增加1或减少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;
}
答案 0 :(得分: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. \n\n";
cin >> choice;
}
if (choice == 1)
minguess = current;
else if (choice == 2)
maxguess = current;
} while (choice != 3);