生成一定数量的数字的随机数 [英] Generate random number of certain amount of digits
问题描述
我有一个非常基本的问题:
I have a very Basic Question which is :
如何在Swift中创建一个具有20位数字的随机数,没有浮点数,没有负数(基本上是Int)?
How can i create a random number with 20 digits no floats no negatives (basically an Int) in Swift ?
感谢所有答案XD
推荐答案
以下是一些伪代码,可以执行您想要的操作.
Here is some pseudocode that should do what you want.
generateRandomNumber(20)
func generateRandomNumber(int numDigits){
var place = 1
var finalNumber = 0;
for(int i = 0; i < numDigits; i++){
place *= 10
var randomNumber = arc4random_uniform(10)
finalNumber += randomNumber * place
}
return finalNumber
}
非常简单.您生成20个随机数,然后将它们乘以相应的数十,百分之一,数千……应放在的位置.这样,您将保证一定数量的正确大小,但会随机生成将在每个位置使用的数字.
Its pretty simple. You generate 20 random numbers, and multiply them by the respective tens, hundredths, thousands... place that they should be on. This way you will guarantee a number of the correct size, but will randomly generate the number that will be used in each place.
更新
正如评论中所述,您很可能会遇到一个如此长的数字溢出异常,因此您必须在如何存储数字(字符串等)方面有所创意,但是我只是想向您展示一种生成具有保证位数长度的数字的简单方法.另外,考虑到当前代码,您的前导数字很有可能为0,因此您也应对此加以防范.
As said in the comments you will most likely get an overflow exception with a number this long, so you'll have to be creative in how you'd like to store the number (String, ect...) but I merely wanted to show you a simple way to generate a number with a guaranteed digit length. Also, given the current code there is a small chance your leading number could be 0 so you should protect against that as well.
这篇关于生成一定数量的数字的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!