Swift rand()不是随机的 [英] Swift rand() not being random

查看:70
本文介绍了Swift rand()不是随机的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天是我在Swift的第一天,我遇到了一个问题.我正在使用rand生成一个随机数,但是每次我运行代码时,它都会给我相同的结果.

Today is my first day with Swift, and I have run into a problem. I am using rand to generate a random number, but it is giving me the same results every time I run the code.

main.swift:

main.swift:

import Foundation

var player = Player()

for _ in 1..6 {
    println(player.kick())
}

player.swift:

player.swift:

import Foundation

class Player {
    var health = 25
    var xp = 15
    var upgrades = ["kick": 0, "punch": 0]

    func kick() -> Int {
        let range = (3, 7)
        let damage = Int(rand()) % (range.1 - range.0) + range.0 + 1
        return damage
    }

    func punch() -> Int {
        let range = (4, 6)
        let damage = Int(rand()) % (range.1 - range.0) + range.0 + 1
        return damage
    }
}

每次运行代码时,它都会记录以下数字:

Every time I run the code, it logs these numbers:

7
5
5
6
6

我也尝试过:Int(arc4random(range.1 - range.0)) + range.0 + 1,但是它说找不到+的重载,接受了提供的参数

I also tried this: Int(arc4random(range.1 - range.0)) + range.0 + 1 but it said it couldn't find an overload for + that accepts the supplied arguments

我不知道为什么会这样.感谢您的帮助,谢谢!

I have no idea why this would be happening. I'd appreciate some help, thanks!

推荐答案

您永远不要使用rand(),请使用arc4random-这是一个更好的生成器.如果查看其手册页,会发现它具有一个称为arc4random_uniform()的整数范围生成器形式,当模数不是2的幂的幂时,应使用该形式来避免模偏差.我相信以下是您所需要的想要,它在操场上对我有用:

You should never use rand(), use arc4random - it's a much better generator. If you check its man-pages, you'll find that it has an integer range generator form called arc4random_uniform(), which you should use to avoid modulo bias when the modulus is not a power of 2. I believe the following is what you want, it worked for me in playground:

let damage = arc4random_uniform(UInt32(range.1 - range.0) + 1) + UInt32(range.0)

+ 1是因为arc4random_uniform()的上端不包含在内.如果范围是(4,7),则应该出现4、5、6和7.

The + 1 is because the upper end of arc4random_uniform() is non-inclusive. If your range is (4,7), this should give occurrences of 4, 5, 6, and 7.

这篇关于Swift rand()不是随机的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆