I am trying to make a number guessing game and I have ALMOST everything working. The number generator, however, does not work properly. It only generates the number 1, so some help would be nice.
#include <iostream>
#include "main.h"
int main(void)
{
using std::cout;
using std::cin;
int guess, num = random(1, 25);
char response;
do {
cout << "\nWelcome to Number Guessing Game\n\n";
cout << "Guess a number between 1 and 25: ";
cin >> guess;
if (guess == num)
{
cout << "\n\nYou have guessed correctly! The number was: " << num;
}
else {
cout << "\n\nSorry. That guess was incorrect. The number was: " << num;
}
//Protection loop - begin
do {
cout << "\nDo you want to play again?(y/n) ";
cin >> response;
} while (response != 'y' && response != 'n');
//Protection loop - end
} while (response == 'y');
return 0;
}
The problem is this line rand_num = low+int(range*rand()/(RAND_MAX + 1.0));
The multiplication is done before the division, so there is a big chance that range*rand() will cause overflow.
The "rand () % (range)" portion will generate a pseudo-random number, then get the remainder of said number divided by the range. This effectively gets a number within the range you want, but it is between zero and said range, so you need to add low to ensure that the number will always be between low and high.
This is being called outside of the loop, so even if it is properly generated at the start of the program, it will be the same number every time the user wants to guess. It's okay to declare the variables here, but call num = random(1, 25);
inside of your loop.