INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Random Numbers

Random Numbers

(OP)
Hi everyone,

I have a problem that seems really simple but I've been having a tough time with it. I want to assign random values in increments of 30, starting at 100, to some "customer" objects let's say. So, customers can have values 100, 130, 160, 190, 220 (assume 220 is the max). Now, I know one solution would be to do something like this:

int myNum = rand() % 5;
if (myNum == 0) {
   return 100;
} else if (myNum == 1) {
   return 130;
} ... and so on.

But I don't like using "magic numbers" and this just doesn't seem to be the right way...I mean what if my range was from 100 to 10000. Obviously I wouldn't want to have that many if statements. I've tried using enums, but that didn't work exactly like I wanted either...but maybe I was just not doing it right.

Any suggestions please?

RE: Random Numbers

Hi

Two ways :
  • if the step is always 30, then calculate it
  • otherwise store them in an array

CODE

int myNum=rand()%5;

int myVal[]={100,130,160,190,220};

printf("for rand %d picked %d and calculated %d\n",myNum,myVal[myNum],myNum*30+100);
 

Feherke.
http://free.rootshell.be/~feherke/

RE: Random Numbers

(OP)
Thank you, that was exactly what I was looking for...and it was super easy, I don't know why I didn't think of that!!

RE: Random Numbers

What's a problem? Keep it simpler:

CODE

int mynum = 100 + rand() % 5 * 30;
Modify coefficients if you wish...
 

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close