Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random Numbers 1

Status
Not open for further replies.

SurvivorTiger

Programmer
Jul 9, 2002
265
US
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?
 
Hi

Two ways :
[ul]
[li]if the step is always 30, then calculate it[/li]
[li]otherwise store them in an array[/li]
[/ul]
Code:
[maroon]int[/maroon] myNum[teal]=[/teal][COLOR=darkgoldenrod]rand[/color][teal]()%[/teal][purple]5[/purple][teal];[/teal]

[maroon]int[/maroon] myVal[teal][]=[/teal][teal]{[/teal][purple]100[/purple][teal],[/teal][purple]130[/purple][teal],[/teal][purple]160[/purple][teal],[/teal][purple]190[/purple][teal],[/teal][purple]220[/purple][teal]}[/teal][teal];[/teal]

[COLOR=darkgoldenrod]printf[/color][teal]([/teal][green][i]"for rand %d picked %d and calculated %d[/i][/green][lime][i]\n[/i][/lime][green][i]"[/i][/green][teal],[/teal]myNum[teal],[/teal]myVal[teal][[/teal]myNum[teal]],[/teal]myNum[teal]*[/teal][purple]30[/purple][teal]+[/teal][purple]100[/purple][teal]);[/teal]


Feherke.
 
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!!
 
What's a problem? Keep it simpler:
Code:
int mynum = 100 + rand() % 5 * 30;
Modify coefficients if you wish...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top