arc4random:限制生成的随机数的值
构建了一个 iPhone 应用程序,当按下按钮时,该应用程序会为标签生成一个随机数。
它工作正常,但我输入的任何值似乎都不会限制生成的随机数的值。它始终是 9 位数字。
-(IBAction)genRandnum:(id)sender {
NSNumber *randomNumber = [NSNumber numberWithInt: (arc4random() % 5) + 1];
NSNumber *randomLabeltxt = [[NSString alloc] initWithFormat:@"It worked!", randomNumber];
randLabel.text = [NSString stringWithFormat: @"%d", randomLabeltxt];
[randomLabeltxt release];
}
正如您所看到的,我在 % 符号后面放入了 5,但它生成了 9 位数字。
Built an iPhone app that generates a random number to a label when a button is pressed.
It works fine, but any value I put doesn't seem to limit the value of the random number generated. it's always 9 digits.
-(IBAction)genRandnum:(id)sender {
NSNumber *randomNumber = [NSNumber numberWithInt: (arc4random() % 5) + 1];
NSNumber *randomLabeltxt = [[NSString alloc] initWithFormat:@"It worked!", randomNumber];
randLabel.text = [NSString stringWithFormat: @"%d", randomLabeltxt];
[randomLabeltxt release];
}
As you can see, I've put 5 in after the % sign, but it generates 9 digit numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSNumber 是一个 Objective-C 对象,因此您应该使用
%@
来显示它。%d
显示一个 9 位数字,因为这是该 NSNumber 的地址。NSString 与 NSNumber 不同。
正确且简化的代码应如下所示:
NSNumber is an Objective-C object, therefore you should use
%@
to display it.%d
shows a 9 digit number as that's the address of that NSNumber.NSString is not the same as an NSNumber.
The correct and simplified code should look like: