在iOS中生成范围内的随机数? [英] Generate random number in range in iOS?
问题描述
我正在尝试在iPhone上使用随机数生成器。标签和按钮有两个文本字段。在一个文本字段中输入最小数字,在下一个文本字段中输入最大值。单击该按钮将在UILabel中显示随机数。我曾经这样做过一次,并且无法弄明白今天的生活。我可以访问的任何代码或地点都很棒。
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.
谢谢
推荐答案
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.
更新:
看来它最好使用 arc4random
而不是 rand
你可以看到更多关于它的信息here 。只需用 arc4random
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
这篇关于在iOS中生成范围内的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!