views:

48

answers:

3

I would like to create just one random number but instead a new random number is being made every time the button is clicked. Where should i put the random number declaration so that it only creates one random number?

+1  A: 

Try seeding the random number generator with a constant. Maybe try:

srand(1);

Of course, for testing purposes, you might want to use a variable so you can change it and have a different "same random number".

The other way would be to use a flag (named something like randomNumIsGenerated) to determine if the number has been generated. The first time you generate, set it to true, and then your code to generate could look like this:

if (!randomNumIsGenerated)
{
   /*generate random number*/
   randomNumIsGenerated=true;
}

randomNumIsGenerated would have to be static, otherwise, each instance of whatever class contains it will have its own random number that only gets set once. Making it static will ensure all instances use the same random number.

Or finally, you could set the random number once, when the program starts up, probably in your startup function (Main, or whatever you've called it).

FrustratedWithFormsDesigner
A: 

You can do something like this:

- (IBAction)buttonPressed:(id)sender {
    static int randomNumber = -1;
    if (randomNumber == -1) {
        randomNumber = arc4random() % (/* maxNumberYouWantGenerated */) + 1;
    }

    ... // do stuff with the random number.
}

The arc4random() function is probably the best random number generator available (rand() and random() have a tendency to not produce all that random numbers), and calling it with no parameters will make it seed itself, so you're good on that account.

The static keyword means that randomNumber will be initialized to -1 when the method is first called, but will remain the same value every time after that (meaning that once it has been generated, the random number will stay the same). You can then use randomNumber knowing that it will be the same random number every time.

All you have to do is decide on the maximum number you want to generate, and put that into the method.

itaiferber
A: 

Rather than ensuring only one number is generated, you could simply disable the button (whichever button that happens to be) using -(void)setEnabled:(BOOL), which NSButton inherits from NSControl. Under iOS, UIControl has an "enabled" property that serves the same purpose. It isn't certain what option is best since the problem description is so sparse. Give us some more details so we can provide better help.

outis