what is the correct way for doing this?

i have a small program and want ppl to type in a value from 0-255, lets call that value INPUT, and basically generate a random number between 0-100, lets call that value RAND and compare INPUT and RAND.

the higher value INPUT is, the less chance you will receive a failed msg, and the lower the value RAND is the less chance you will receive a failed msg, but if RAND is 100 you will receive a failed msg no matter what, so does anyone know what is the best way of doing the math for something this in c++?
Last edited on
I = INPUT + 1 ∈ [1, 256]
R = 100 - RAND ∈ [0, 100]
therefor: I * R ∈ [0, 25600]
let R' = another random number ∈ (0, 25600]
if( R' <= I * R )
    print "Success"
else
    print "Fail"

Of course, this is just one way of doing it.
Last edited on
> want ppl to type in a value from 0-255 ...

You need to read an int from stdin, verify that an integer in the range (0-255) was entered and if the validation failed, ask the user for input again. Something like:
1
2
3
4
5
6
7
8
9
10
11
12
    // accept an integer in (0,250) from stdin
    int input = -1 ;
    do
    {
        std::cout << "integer (0-250)? " ;
        if( !( std::cin >> input ) )
        {
             std::cin.clear() ;
             std::cin.ignore( std::numeric_limits<std::streampos>::max() ) ;
        }
    }
    while( ( input < 0 ) || ( input > 250 ) ) ;



> generate a random number between 0-100

Use the facilities available in the header <random> For example:
1
2
3
4
    // generate a random number uniformly distributed in [0-100]
    std::mt19937 engine( std::time(0) ) ;
    std::uniform_int_distribution<int> distribution(0,100) ;
    int random_number = distribution(engine) ;


Why not just use an unsigned char for the input variable? That goes from 0 to 255.

-Albatross
Mathhead, your example was almost perfect, however i wanted people who enter the value 0 to still have a decent % of getting a success msg, but in your example the chances of that are very small since (INPUT 0 is 1) * (RAND lowest is 1 so 100-1 = 99) that would be 1 * 99 = 99, and to get another random generator from 0, 25600 to be under 99 is very low.
Instead of something linear, try something logarithmic or try a power function with the exponent < 1 instead. Or, if you like linear, give it a bigger offset (intercept.)
Last edited on
Topic archived. No new replies allowed.