guyster104
asked on
a math game for some kids
I am trying to write a math program for some kids I work with who are visually impaired and just need a little advice on a couple issues. For one, I'm writing the program in C, and I'm trying to generate random numbers for the problems which are asked. I seeded the generator with srand((unsigned)time(NULL) ) at the beginning and am trying to exclude 0 from being generated as a possible number for a problem. For example: firstint = rand()%maxint. Maxint is defined according to how far the player has progressed in the game. I want the generated number to be between 1 and maxint. Any suggestions? Thanks a lot in advance.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
1 + rand() % (MaxInt-1); will never return a value of MaxInt
why wouldnt it?
Say MaxInt = 5
I have took one away from MaxInt so,
the line of code could look like
rand() % 4
That means a number between 0 and 4 could be generated. The I have added one to the result so a number between 1 and 5 can be generated.
If your talking about the order of precedance guyster should use:
FirstInt = (rand() % (MaxInt-1)) + 1
Say MaxInt = 5
I have took one away from MaxInt so,
the line of code could look like
rand() % 4
That means a number between 0 and 4 could be generated. The I have added one to the result so a number between 1 and 5 can be generated.
If your talking about the order of precedance guyster should use:
FirstInt = (rand() % (MaxInt-1)) + 1
Its been a few years since I have used C, so the loop construct is probably wrong, but the concept is there.
If you are not too sure about what Max & Min values you may end up with, you could always build in a safety net.
do
FirstInt = 1 + rand() % (MaxInt-1);
until Firstint >=1 and FirstInt <=MaxInt
If you are not too sure about what Max & Min values you may end up with, you could always build in a safety net.
do
FirstInt = 1 + rand() % (MaxInt-1);
until Firstint >=1 and FirstInt <=MaxInt
ASKER
Ozo's method worked well. The program is well on its way to completion. I would love to spice it up with some visual elements, such as dialogue boxes and a Windows style interface, but since I myself am visually impaired, don't know if I want to brave that one just yet. Thanks to all for the suggestions. Keep up the good work.
Guy
Guy
FirstInt = 1 + rand() % (MaxInt-1);