arc4random:限制生成的随机数的值

发布于 2024-09-26 00:01:37 字数 484 浏览 7 评论 0原文

构建了一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑着哭最痛 2024-10-03 00:01:37
  1. NSNumber 是一个 Objective-C 对象,因此您应该使用 %@ 来显示它。 %d 显示一个 9 位数字,因为这是该 NSNumber 的地址。

  2. NSString 与 NSNumber 不同。

正确且简化的代码应如下所示:

int randomNumber = (arc4random() % 5) + 1;
// no need to create an NSNumber if you do not need to store it into an NS container.

randLabel.text = [NSString stringWithFormat:@"It worked! %d", randomNumber];
// no need to create an intermediate NSString variable.
//  you can directly assign the string to the label's text.
  1. 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.

  2. NSString is not the same as an NSNumber.

The correct and simplified code should look like:

int randomNumber = (arc4random() % 5) + 1;
// no need to create an NSNumber if you do not need to store it into an NS container.

randLabel.text = [NSString stringWithFormat:@"It worked! %d", randomNumber];
// no need to create an intermediate NSString variable.
//  you can directly assign the string to the label's text.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文