C++ Random Numbers
why does this still output really big numbers such as 25032, 11158, and 30849? Also how come it it does not say "Your roll is " and "My roll is "? here's the code.
#include <cstdlib>
#include <time.h>
using namespace std;
const int LOW = 1;
const int HIGH = 25;
int main()
{
int first_die, sec_die;
time_t seconds;
time (&seconds);
srand((unsigned int) seconds);
first_die = rand() & (HIGH - LOW + 1) + LOW;
sec_die = rand() & (HIGH - LOW + 1) + LOW;
cout<< "Your roll is (" << first_die <<", "
<< sec_die << ")" << endl << endl;
first_die = rand() & (HIGH - LOW + 1) + LOW;
sec_die = rand() & (HIGH - LOW + 1) + LOW;
cout<< "My roll is (" << first_die << ", "
<< sec_die << ")" << endl << endl;
return 0;
}
im doing this from a tutorial and i double checked to make sure everything was the same (excluding the comments) and it was. so im not sure whats wrong. I also ran the one straight from the tutorial, and it didn't work either, it didn't output the text, and it gave big #'s. Thanks for your time. end3r
Because you are using the Bitwise AND operator instead of the modulus operator which is '%'. Also there is no need to declare your constants as global, declare/define them within main(). Also, make sure you are using <ctime> and not <time.h> because it is a deprecated header file. And personally, I just go with..
//seed random number generator
srand((unsigned int) time(0));
//choose a random number between 1 and 5
int myRandVal = rand() % 5 + 1;
Cheers, ~T
Thanks, but how do i declare my constants within main?
markupint main( const int LOW = 1, const in HIGH = 25 )
?
Here's my new code, but it still doesn't output the text?
#include <cstdlib>
#include <ctime>
using namespace std;
int main( const int LOW = 1, const int HIGH = 25 )
{
int first_die, sec_die;
time_t seconds;
time (&seconds);
srand((unsigned int) seconds);
first_die = rand() % (HIGH - LOW + 1) + LOW;
sec_die = rand() % (HIGH - LOW + 1) + LOW;
cout<< "Your roll is (" << first_die <<", "
<< sec_die << ")" << endl << endl;
first_die = rand() % (HIGH - LOW + 1) + LOW;
sec_die = rand() % (HIGH - LOW + 1) + LOW;
cout<< "My roll is (" << first_die << ", "
<< sec_die << ")" << endl << endl;
return 0;
}
Thanks again, end3r
You'd declare them in main() just like any other variable..
Modified Code:
#include <iostream>
#include <ctime>
int main(int argc, char **argv)
{
const unsigned int LOW = 1, HIGH = 25;
unsigned int first_die, sec_die;
srand((unsigned int) time(0));
first_die = rand() % (HIGH - LOW + 1) + LOW;
sec_die = rand() % (HIGH - LOW + 1) + LOW;
std::cout << "Your roll is (" << first_die <<", "
<< sec_die << ")" << std::endl;
first_die = rand() % (HIGH - LOW + 1) + LOW;
sec_die = rand() % (HIGH - LOW + 1) + LOW;
std::cout << "My roll is (" << first_die << ", "
<< sec_die << ")" << std::endl;
return 0;
}