C++ | Generating a pseudo number between 10-20

2019-02-09 04:26发布

I am making a text-based C++ RPG and I am trying to figure out how to work out the amount of damage that the enemy hits you for. My idea is something like this.

Damage done = randomIntBetween10and20*enemyLevel

This way it doesn't always hit for a set amount each time and allows there to be Critical Strikes (For example, if the hit is above 15 I would class that as a Critical Strike)

I'm new to C++ so I'm not quite sure how I can do this, any help would be greatly appreciated.

标签: c++ random
9条回答
孤傲高冷的网名
2楼-- · 2019-02-09 05:18

look this out, it might be helpful:

// random numbers generation in C++ using builtin functions
#include <iostream>

using namespace std;

#include <iomanip>

using std::setw;

#include <cstdlib>   // contains function prototype for rand

int main()
{
// loop 20 times
for ( int counter = 1; counter <= 20; counter++ ) {

    // pick random number from 1 to 6 and output it
    cout << setw( 10 ) << ( 1 + rand() % 6 );

    // if counter divisible by 5, begin new line of output
    if ( counter % 5 == 0 )
        cout << endl;

}

return 0;  // indicates successful termination

} // end main
查看更多
疯言疯语
3楼-- · 2019-02-09 05:23

Use srand() to initialise the random number generator:

sand(time(NULL));

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

Then use the rand() function to generate a sequence of random numbers.

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

查看更多
孤傲高冷的网名
4楼-- · 2019-02-09 05:26

As others said, maybe rand() will be really sufficient for you. What is important is the seed used to initialise the pseudo random number generator ( the call to srand() is the seed)

But beware, True Chaos doesnt mean that you have exactly the same chance to generate any possible random output.

Ten years ago I have played with stochastic sound generation. I needed several sources of chaos.

I just let you know those which I had kept and found useful. of course since they need a seed, they are pseudo chaos.

1/for chaotic float number between -1 and 1: compute the function f(x) = cos(exp(x)). exp() grows so fast, that after really few iteration, what goes out from cos() is chaos.

2/the baker transform: chaotic number between 0 and 1: take a number, multiply it by two, and again, when it is superior to 1, substract something so as it goes back betwen 0 and 1. A much more precise explanation The Baker Transform.

But I think rand() and srand() will satisfy you.

For applying to your range 10-20, of course you stretch/scale the chaotic range (0;1) or (-1;1) by multiplying and offsetting so as the ouput fits your need. ;-)

查看更多
登录 后发表回答