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.
How about double random? def doublyRandom(): rand = random() multiplier = ( max - min ) * rand() multiplier = multiplier + min * rand return( multiplier * rand() )
I am a beginner, @rsmith6559, the assignment wants me to use random() and write an algorithm that will work for any range.
@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
#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; }
where "%" is a modulo operator
correction: return ((rand()%(max-min)) + min);
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
Join our real-time social learning platform and learn together with your friends!