生成一定数量的数字的随机数

编程入门 行业动态 更新时间:2024-10-24 14:17:03
本文介绍了生成一定数量的数字的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个非常基本的问题:

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.

更多推荐

生成一定数量的数字的随机数

本文发布于:2023-11-29 00:25:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644559.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   数量   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!