问题描述
喂,
我有一个非常基本的问题:
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.
这篇关于生成一定位数的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!