Important notes on rand():
rand( value % 100 ) is in the range 0 to 99
rand( value % 100 + 1 ) is in the range 1 to 100
rand( value % 30 + 1985 ) is in the range 1985 to 2014
Everything else in the code seems self explanatory, tell me if it isn't.
First you need to seed your rand in order to get different results each time you start the program. If you don't everytime you start the program it will be the same result, as illustrated in this example:
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int range_hit = 17;
int r = rand()%20;
cout << "Random number is " << r << endl;
if(r<=range_hit)
{
cout << "The bull was hit!";
}
else
{
cout << "Aww you missed";
}
return 0;
}
Here is the seeded code, this chnages the rand to coresond to miliseconds on your computerclock:
Code:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void seedrnd(void);
int main()
{
seedrnd();
int range_hit = 16;
int r = rand()%20;
cout << "Random number is " << r << endl;
if(r<=range_hit)
{
cout << "The bull was hit!";
}
else
{
cout << "Aww you missed";
}
return 0;
}
void seedrnd(void)
{
srand((unsigned)time(NULL));
}
I'm not very good so there might be a mistake...