Our next task was to build a random number generator wth a C++ program. This was the first time I ever did something like that. I tried unsuccesfully to do it by myself at first, but I just couldn´t figure out what to do. So I decided to check what the Oracle of Google had for me. I came up with this information, basically the first webpage on the list. I also checked out a video from my Yankee tutor on Youtube, thenewboston.
The program basically works with a do while loop, so you can keep guessing until you hit the correct number. Also, I you miss, it is programmed to tell you wether you gave a higher number or a lower number. I did this with an If cycle.
- About the random number, it works with the function rand, contained in the header #include <stdlib.h>
- In order fot the numbers to never be predictive, I used the function time, as a paramater of srand. As a paramater of time I used 0, as thenewboston explained, this would make the time to use he number of seconds since it was developed, probably in the 70´s. PEACE.
- So, now the numbers should be really hard to predict.
- In order to only get random numbers between 0 and 100, we had to use the modulus 100 + 1 of the function rand()
So no more talking, the code can tell a thousend words:
“Dead men tell no tales” ARGGGHH
Sorry Blackbeard, go back to the XVII century bro.
Have a look at my code:
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
int main ()
{
int x, y;
srand (time(0));
x = rand() % 100 + 1;
do {
cout << “Guess a
(1 to 100): ” << endl;
cin >> y;
if ( x < y)
cout << “The number is lower” << endl;
else if ( x > y )
cout << “The number is higher” << endl;
} while (y != x);
cout << “Congrats! You´ve guessed the number”;
return 0;
}
Random number generator by netosanchezb is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.