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.
这篇关于生成一定位数的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:生成一定位数的随机数
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01