问题描述
所以我在这个代码位的目标是随机掷两个骰子,众所周知,您的普通骰子只有6个面,因此我导入了Foundation以访问arc4random_uniform(UInt32)。我尝试使用(1..7)的范围来避免随机获得0,但是返回了一个我不太喜欢的错误。我试图这样做:
so my goal in this codebit is to randomly roll two dice and as we all know your regular die only has 6 sides so I imported Foundation for access to arc4random_uniform(UInt32). I attempted using the range of (1..7) to avoid randomly getting 0 however that returned an error which I didn't enjoy too much. I tried to do this:
dice1 = arc4random_uniform(UInt32(1..7))
无论如何返回
我希望这对您来说是足够的信息,令人惊奇的deb可以帮助我: )
I hope that this is enough information for you amazing debs out there to help me :)
请注意,我只是在操场上练习快速动作。我不必学习如何做到这一点;这只是我在开始构建实际应用程序之前的修正:D
Please note I am just doing this in a playground to practice swift. It isn't imperative that I learn how to do this; it's just me tinkering before I jump into building actual apps :D
//imports random number function
import Foundation
//creates data storage for dice roll
var dice1: UInt32 = 0
var dice2: UInt32 = 0
//counter variable
var i = 0
//how many times snake eyes happens
var snakeeyes = 0
//how many times a double is rolled
var `double` = 0
//rolls dice 100 times
while i < 100{
//from here
//sets dice roll
此返回错误'Range $ T3'不能转换为UInt32
This returns an error of 'Range $T3' is not convertible to UInt32
dice1 = arc4random_uniform(1..7)
dice2 = arc4random_uniform(1..7)
//checks for snake eyes
if dice1 == 1 && dice2 == 1 {
snakeeyes = snakeeyes + 1
}
//checks for doubles
if dice1 == dice2{
`double` = `double` + 1
}
//increases counter
i = i + 1
//to here
}
println("You got Snake Eyes \(snakeeyes) times.")
println("You got Doubles, \(`double`) times.")
推荐答案
我相信您应该
dice1 = arc4random_uniform(6) + 1;
得到范围1-6。我不做iOS目标C,也不知道虽然很快。随机方法应返回0到5之间的值,而+ 1将使其变成1到6之间的值。
to get the range 1 - 6. I don't do iOS objective C nor have I any knowledge on swift-language though. The random method should return a value between 0 and 5, and + 1 will make it a value between 1 and 6.
如果您需要介于10之间的范围- 30然后做
If you need a range between lets say 10 - 30 then just do
int random = arc4random_uniform(21) + 10;
这篇关于如何在arc4random_uniform()的范围之间产生随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!