hi i would like u to tell me if i can make a random function to choose between four numbers and only them(-1 , 1 , -10 ,10)

Recommended Answers

All 7 Replies

/*
say numbers are 2,8,15,51 
so upperLimit=51 & lowerLimit=2
*/
int num;
do
  num=rand((51-2)+1)+2;    //This I deliberately did to denote uLimit & lLimit
while(num!=n1 && num!=n2 && num!=n3 && num!=n4);

rand(x) will always return a number from 0 to (x-1).

thanx nbaztec for your answer but if the numbers are -1,1,10,-10
the command will be like :num=rand((10-10)+1)+2;

num=rand((10-10)+1)+2;

I deliberately made the code that way so you could understand, but looks like you made a slight mistake:

rand((uLimit-lLimit)+1)+lLimit
equals
rand((10-(-10))+1)+(-10)

since uLimit=10 & lLimit=-10

hi i would like u to tell me if i can make a random function to choose between four numbers and only them(-1 , 1 , -10 ,10)

Yes, you can. Quite easily, in fact:

int a[] = { -1, 1, -10, 10 };
int choice = a[rand() % 4];

rand(x) will always return a number from 0 to (x-1).

No, rand will always return an integer in the range of [0, RAND_MAX). rand doesn't take any parameters. On top of being overly complicated, your code is flat out wrong. Perhaps you were thinking of one of the many non-portable alternatives (not called rand) that compilers like to offer?

commented: Thanks for correcting me. :) +1
int a[] = { -1, 1, -10, 10 };

Why didn't I think of that before. Great!

rand(x) will always return a number from 0 to (x-1).

Apologies. I meant the random() function. I know it's not standard but I grew up with it. :)

I know it's not standard but I grew up with it.

Of course Murhpy's law says that the instant you offer a non-portable solution, people shoot back with "it doesn't work". Then there's the subsequent bout of twenty questions to reach the conclusion that their compiler doesn't support the feature and a standard solution would be better.

That's a real pain, so we just go straight to the standard solution in the first place and avoid the headache.

Well Put. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.