Ask your own question, for FREE!
Computer Science 20 Online
OpenStudy (onepieceftw):

I need to write a program that the user sets a range of numbers (e.g. 30 -50) It needs to select a random number inside this range.

OpenStudy (rsmith6559):

How about double random? def doublyRandom(): rand = random() multiplier = ( max - min ) * rand() multiplier = multiplier + min * rand return( multiplier * rand() )

OpenStudy (onepieceftw):

I am a beginner, @rsmith6559, the assignment wants me to use random() and write an algorithm that will work for any range.

OpenStudy (woodrow73):

@OnePieceFTW You'll probably want a look at the Random class's nextInt() method http://www.tutorialspoint.com/java/util/random_nextint_inc_exc.htm

OpenStudy (fifciol):

#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int random_number(int min, int max) { return ((rand%(max-min)) + min); } int main() { int min, max; srand( time( NULL ) ); cout<<"Enter min value: "; cin>> min; cout<<"Enter max value: "; cin>> max; cout<<"Random number from "<<min<<"to"<<max<<" is <<random_number(min, max); return 0; }

OpenStudy (fifciol):

where "%" is a modulo operator

OpenStudy (fifciol):

correction: return ((rand()%(max-min)) + min);

OpenStudy (fifciol):

rand() is some arbitrary number, modulo range (max - min) gives you namber from this range. + min, gives you number from min to (max - min) + min so at the end you got number from min to max

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!