First post! So I am a beginner programmer learning about to program, and I have a question in particular about random numbers. I am basing me code of the book for my school. After reading it, the code tells me I should do the code like this. The problem with this is that every time I compile it, it just does not seem random to me and it goes up by 3 every time.
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
unsigned seed = time(0);
srand(seed);
const int MIN_VALUE = 1;
const int MAX_VALUE = 100;
cout << (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE << endl;
return 0;
}
Then after specifically following me book that is required for my course, I decided to do this followed by what the book told me. It still goes up by 3 and does not seem very random to me!
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
unsigned seed = time(0);
srand(seed);
const int MIN_VALUE = 1;
const int MAX_VALUE = 100;
double y;
y = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
cout << y << endl;
return 0;
}
Then after countless of minutes, I tried to play around with it and I got the solution for true randomness, but I have no idea why it works. I am literally defining it twice, but in the book it goes it once. Thank you all for reading and hope to get fast responses! :)
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
unsigned seed = time(0);
srand(seed);
const int MIN_VALUE = 1;
const int MAX_VALUE = 100;
double y;
y = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
cout << (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE << endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire