quick question

Started by
5 comments, last by hothead 19 years, 6 months ago
quick question. how do I get the computer to generate a random number between 2 numbers. lets say for example, it randomly chooses between 1-3. how would i do this. any help is greatly appreciated.
You can leave and beat the traffic or you can stay and beat your meat.Blink 182
Advertisement
i don't know if this is what your looking for but
#include<iostream>#include<ctime>#include<cstdlib>using namespace std;int main(){   srand(time(0));   int num = ((rand() % 3) + 1);   cout<<num;   int x;   cin>>x;    return 0;}
-----------------------------------Panic and anxiety Disorder HQ
in C:
int random(int low, int high){  return low + (rand() % (high - low + 1));}
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
Language? Platform?

The typical C solution is to obtain the modulus of the rand() function and the upper bound. This has problems with certain implementations of the C runtime because the lower bits have less randomness than the overall value.
In C.

number=rand()%2; //0-1
number=rand()%3; //0-2
number=rand()%4; //0-3
number=(rand()%2)+1; //1-2
number=(rand()%2)+3; //3-4
*G*

I saw no answers when i started writing my post, that was fast!
sorry i should have said what language. C++ and i figured it out shortly after posting :P but thanx for the replys.
You can leave and beat the traffic or you can stay and beat your meat.Blink 182

This topic is closed to new replies.

Advertisement