Thursday, July 30, 2009

How can I make a program that gives a random number with user specified limits and decimal places in function?

I need to do a program that has Upper and lower limits to the random number it will give. The program must be in functions and display a number between the limits %26amp; with the user specified decimal places. PLEASE HELP - CALLING ALL PROGRAMERS!! SOS! THE LANGUAGE IS C++ COMAND LINE

How can I make a program that gives a random number with user specified limits and decimal places in function?
Most languages have a random number function that will return a pseudo-random number between 0 and 1. Basically, what you would do is


input maximum number


output = random number * maximum number.





You can format the output to show the correct number of digits.
Reply:I USED:


fixed%26lt;%26lt;setprecision(dígDec) //and


(static_cast %26lt;double%26gt;


((static_cast %26lt;long%26gt;


(límInferior * pow(10.0,dígDec) + 1 + rand()


%


static_cast %26lt;long%26gt;


(límiSup * pow(10.0, dígsDec)-


límInf * pow(10.0, dígsDec))


))


/ pow( 10.0 , dígDec))) Report It

Reply:If you're allowed to use the library random-number function, then it's simply a matter of scaling that function's return value to the range the user specified - so if the function returns a number in the space (0,1), and the user specifies the range as 3,7, you just need to return 4*function() + 3.





If you need to generate a pseudorandom number yourself, it gets trickier, especially if you want a *good* random number generator. Linear-contruent functions are often "good enough" for shortprograms.





And remember that '390' is a perfectly good random number. (In other words, a single number *can't* be random - what is random is a *sequence* of numbers - the less correlation between sequence members, the more random the sequence is).
Reply:the sample code below will generate random number from 1 to 10. you may change the value of lowest and highest variable to generate different range of random numbers.





int random_integer;


int lowest=1, highest=10;


int range=(highest-lowest)+1;


for(int index=0; index%26lt;20; index++){


random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));


cout %26lt;%26lt; random_integer %26lt;%26lt; endl;

our song

No comments:

Post a Comment