[C++] Random Numbers help

Status
Not open for further replies.
Junior Spellweaver
Joined
Jun 10, 2008
Messages
117
Reaction score
0
Hello, i am currently making a text RPG but for specific monsters i want their damage to be withing a certain range of number and then choose them randomly. Please help
 
what if i want it between like 13 and 20?

Google on how to get a random number, then take using what you found, a random number that goes from 0 to MAX - MIN, then make the result plus MIN.
from 13 to 20 would be a number from 0 to 7(or 8 if the last number is not include, I dont remember)
if the result is 0, plus 13 = 13(min)
if it is 7, plus 13 = 20(max).

You can also use an algorithm like MersenneTwister, google for that also.
 
(rand() * (High - Low - 1)) + Low;
Generates a random number between [Low, High) (e.x from Low <= number < High)

That or using modulo is really the only two ways I've ever seen it done.
 
Modulo divides A by B and returns the rest:

5 % 2 = 1 (because 5 / 2 = 2.5, rest is 0.5 * 2 = 1).
9 % 5 = 4

So, if you get a random number, you first limit it's range (and still keep it random) by using the modulo operation. Then you can add or subtract to the whole range to move it around. Pretty straightforward.

Code:
#include <iostream>
#include <cstdlib>

int main()
{
    unsigned int max = 500, min = 100;

    if ((max - min) > RAND_MAX)
    {
        std::cerr << "Range overflows the maximum of rand();\n";
    }

    while (1)
    {
        unsigned int random = (rand() % ((max - min) + 1))) + min;
        std::cout << random << '\n';
    }
    //return 0;
}
 
I tried using your example Team Lion and when i put it in like this
Code:
case 1:
                                   cout << "The walking Mushroom attacks!\n";
                                   unsigned int  UHP - (rand() * (8 - 2 - 1)) + 2;
                                   cout << "You now have " << UHP << " Health Points left!\n";
                                   system("pause");
It won't change
 
Why don't you get a compile error, the minus ( - ) behind UHP when trying to define it should be an is ( = ).

Also, it is advised to use brackets for case statements.
 
I do use case statements. i didn't get a error because it is a valid operation. and i still need information on the question at hand.
 
Then how come i have yet to see you fix my problems? The only stuff you put on here are things that are not answering my question.
 
We're trying to help you, not just answering your exact questions, we aren't slaves.

Now figure it out yourself, you've got your random-number questions answered.
 
Status
Not open for further replies.
Back