I'm new to Xcode development, and i would like to know how can i generate random numbers from 2 inputs.
In IB i have 2 textfields (with Number pad) that i开发者_高级运维ndicate the interval of the numbers to generate (i.e. from 3 to 7). I would like to know how i get the inputs from the 2 textfields and do a method that generate random numbers from these inputs.
There are many issues involved in trying to generate a truly random number. Note, for instance, that functions like rand() and random() generate sequences of numbers based on a 'seed value'. That means that if the seed value is the same, the sequence of numbers generated will be the same. There are various ways to use 'random' seeds - ie., using the current date and time - but the reliability and security of these methods is questionable.
As the number generators evolve, these issues get addressed, and therefore the later generators are usually better than the earlier ones: rand is generally not as random as random, and random is not as random as arc4random.
The current problem with arc4random(), which is documented in their manual pages, is that using a modulus calculation - as in "arc4random() % UPPER_LIMIT" - can introduce statistical bias, if UPPER_LIMIT is not an even number. Because of this, a new function was added to the arc4random family, called arc4random_uniform. It produces evenly distributed random numbers, regardless of the upper limit - and it is quite simple to use.
Using your example above, I would recommend you try generating your random number like this:
int value = low_bound + arc4random_uniform(width + 1);
int low_bound = 3;
int high_bound = 7;
int width = high_bound - low_bound; // 4
int value = low_bound + arc4random() % (width + 1); // 3 + 0..4
Plus read the bounds from the fields, something like bound = [[field text] intValue]
.
If you have trouble connecting the input fields to the code, you should read some Cocoa tutorial. There are several ways to do it, one of the most straightforward is declaring properties for the text fields in the controller class:
@interface Controller : UIViewController {}
@property(retain) IBOutlet UITextField *lowerBoundField;
@property(retain) IBOutlet UITextField *upperBoundField;
@end
Then you can connect the text fields in the Interface Builder to these outlets and work with them in code like this:
- (void) generateNumber {
int lowerBound = [[lowerBoundField text] intValue];
…
}
This is assuming we are talking about Cocoa Touch. In desktop Cocoa the situation is similar, just the details would be different.
精彩评论