/*Instead of increment 1 or decrease 1 the random number in the for loop, I would like the code to generate a random integer higher than the previous random generated if guess is higher and to generate a random integer lower than the previous random generated if the guess is lower./
#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;
}
You just need to call random with your new limits.
To make things easier let us write a function that generates integers between any two limits we specify, say low_limit
and low_limit
.
int random(int low_limit, int up_limit){
return rand() % ((up_limit - low_limit) + 1) + low_limit;
}
Now generate the first number by calling the function and save the result into a temp
variable.
temp = random (0, 100);
Now upon user input you can use temp
to call random
like this:
if (value == higher)
temp = random (temp, 100);
else if (value == lower)
temp = random (0, temp);
For different random numbers each run you can use srand
function with a parameter that can give a different seed each time like system time.
srand(time(NULL));
note: Use the proper headers.
UPDATE
Based on your comments, you can use extra two variables say: minguess
and maxguess
to narrow your random generation range. check the following piece of code:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.