So I\'m doing a simple guess a number program where I create a random number the
ID: 3865791 • Letter: S
Question
So I'm doing a simple guess a number program where I create a random number then ask the user to guess what it is. My code below will do this but here's the weird part, when i compile and run this with a linux machine using notepad++ it does what it's suppose to. But if I compile and run it with Code Blocks, it picks the same random number every single time, 2 in my case. Does anyone know why it would do this?
On a side note, this is not the first time i've had issues with Code Blocks. If you use something like stoi it'll bring up an error when you try to compile, atoi is a way around this but it's still annoying. Any suggestions for a better text editor/compiler?
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int num_guessed;
int random_num = (rand() % 10) + 1; // 1 through 10
do
{
cout << "Guess a number between 1 through 10: ";
cin >> num_guessed;
if (num_guessed > random_num)
{
cout << "Too High ";
}
else if (num_guessed < random_num)
{
cout << "Too Low ";
}
} while (num_guessed != random_num);
cout << " You Win!! ";
return 0;
}
Explanation / Answer
// Well ! this question is asked many times (So i am answering it again)
To stop to generate the same random number
You must use srand (time(NULL)); at the begining of the main function to initialize the seed for rand function
You must include
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.