Haha, this reminds me of something I did awhile back. You should use the while loop. If you want any reference, here was what I did. Only difference with mine is the user gets to input the range. I also recommend seeding the random with time().
cout << "Can you guess the number I am thinking of?" << endl << "First, choose two numbers when prompted." << endl;
// fNumber is the first number the users input, sNumber is the second number the users input.
int fNumber,sNumber=0;
cout << "First Number: ";
cin >> fNumber;
cout << endl << "Second Number: ";
cin >> sNumber;
// For the randNum to work, fNumber has to be bigger than sNumber. This if-statement changes it if it's not.
if (fNumber<sNumber) {
int temp=fNumber;
fNumber=sNumber;
sNumber=temp;
}
cout << string(3, '\n') << "Ok, the number I am thinking of is between " << fNumber << " and " << sNumber << "." << endl;
int guess=0;
// This creates the random number between the two values the user inputed. (fNumber and sNumber)
srand(time(0));
int randNum = rand()%(fNumber-sNumber + 1) + sNumber;
cout << "Can you guess it?" << endl;
while(guess!=randNum) {
cout << endl;
cout << "Guess: ";
cin >> guess;
if (guess < randNum)
cout << "Too low" << endl;
if (guess > randNum)
cout << "Too high" << endl;
}
if(guess==randNum) {
string(4, '\n');
cout << "Nice, you guessed my number!" << endl;
cout << "You get a gazillion points!" << endl;
At the moment, all your code does is ask you once and then it ends. Also you have your operators switched.
It should be like this.
1 2 3 4 5
if (guess > secret) // Your operators were incorrect earlier. This is the correct way.
cout << "Guess is high..." << endl;
if (guess < secret) //Same with this one.
cout << "Guess is low..." << endl;
#include <iostream>
#include <ctime>
#include <cstdlib>
int main(){
srand(static_cast<unsignedint>(time(NULL))); // seed rand numb
int rndNum = rand() % 100 + 1; // I hope you understand why. rand() % 100 + 1 = random number from 1 to 100
int guess;
int tries = 0;
std::cout << "Welcome to Guess-my-Number version 0.1!" << std::endl;
std::cout << "A secret number between 1-100 generated..." << std::endl << std::endl;
// going to use a do while loop so that it executes at least once. i can use a while loop here but i just want to make sure.
do{
std::cout << "Please enter your guess: ";
std::cin >> guess;
++tries; // we want to increment the number of tries every time the guess is incorrect.
if (guess > rndNum)
std::cout << "Too high of a guess! Please try lower." << std::endl;
elseif (guess < rndNum)
std::cout << "Your guess is too low! Please try again." << std::endl;
else
std::cout << "Good job, you've figured out the number after " << tries << " tries!" << std::endl;
} while (guess != rndNum && tries != 8); // If our guess isn't the random number AND our tries aren't equal to 8..
return 0;
}