ios 在iOS中生成范围内的随机数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5601953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate random number in range in iOS?
提问by Frankrockz
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 上工作。有两个文本字段,一个标签和一个按钮。在一个文本字段中输入最小值,在下一个文本字段中输入最大值。单击该按钮将在 UILabel 中显示随机数。我以前做过一次,但我今天的生活无法弄清楚。我可以访问的任何代码或地方都很棒。
Thanks
谢谢
回答by Dair
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
看起来使用它可能更好,arc4random
而不是rand
您可以在此处查看更多相关信息。只需将所有rand
s替换为arc4random
回答by Peter DeWeese
#include <stdlib.h>
int randomNumber = min + rand() % (max-min);