I'm trying to get a random number generator working on the iPhone. There are two text fields a label and a button. Enter the minimum number in one textfield and the maximum in the next. Clicking the button will display the random number in the UILabel. I did this once before and can't figure it out for the life of me today. Any code or places I could visit to find this out would be fantastic.
我想让一个随机数发生器在iPhone上工作。有两个文本字段,一个标签和一个按钮。在一个textfield中输入最小值,然后在下一个textfield中输入最大值。单击按钮将显示UILabel中的随机数。我以前做过一次,但今天我无法理解。我可以访问的任何代码或地方都可以发现这一点。
Thanks
谢谢
2 个解决方案
#1
95
NSString *min = myMinTextField.text; //Get the current text from your minimum and maximum textfields.
NSString *max = myMaxTextField.text;
int randNum = rand() % ([max intValue] - [min intValue]) + [min intValue]; //create the random number.
NSString *num = [NSString stringWithFormat:@"%d", randNum]; //Make the number into a string.
[myLabel setText:num]; // Give your label the value of the string that contains the number.
Update:
更新:
It appears that it is probably better to use arc4random
as opposed to rand
you can see more about it here. Just replace all the rand
s with arc4random
与rand相比,使用arc4random可能更好,你可以在这里看到更多。用arc4random替换所有的r
#2
23
#include <stdlib.h>
int randomNumber = min + rand() % (max-min);
#1
95
NSString *min = myMinTextField.text; //Get the current text from your minimum and maximum textfields.
NSString *max = myMaxTextField.text;
int randNum = rand() % ([max intValue] - [min intValue]) + [min intValue]; //create the random number.
NSString *num = [NSString stringWithFormat:@"%d", randNum]; //Make the number into a string.
[myLabel setText:num]; // Give your label the value of the string that contains the number.
Update:
更新:
It appears that it is probably better to use arc4random
as opposed to rand
you can see more about it here. Just replace all the rand
s with arc4random
与rand相比,使用arc4random可能更好,你可以在这里看到更多。用arc4random替换所有的r
#2
23
#include <stdlib.h>
int randomNumber = min + rand() % (max-min);