生成伪随机数/大写字母 [英] Generating Pseudo Random Number/Capital Letter

查看:119
本文介绍了生成伪随机数/大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

在我的程序中,我必须生成一个随机数/大写字母并将其转换为字符.
在网上,我能够找到一种算法,该算法几乎可以完成以下操作:

Hello everyone,

In my program I have to generate a random number/capital letter and cast it as a char.
Online I was able to locate an algorithm that does nearly that:

int main() {
        srand((unsigned) time(NULL));
        
        const int passLen = 10;
        for (int i = 0; i < passLen; i++) {
                cout << (char) (rand() % ('z' - '0' + 1) + '0');
        }
}



我的问题是,我不完全了解此方法的工作原理,因此,我不确定如何修改该函数以使其执行我想要的操作.任何人都可以大致解释一下此过程的工作方式,以便我可以根据自己的喜好修改此功能吗?

谢谢你,很抱歉这个基本的问题.我对此还很陌生.



My problem is, I don''t completely understand how this method works, and because of this I''m not sure how to modify the function to get it to do what I want. Could anyone please explain approximately how this process works so that I can learn to modify this function to my liking?

Thank you, sorry for the fairly basic question. I''m still pretty new to this.

推荐答案

确定-依次查看:
OK - look at it in parts:
srand((unsigned) time(NULL));

初始化随机数生成器.

Initialises a random number generator.

const int passLen = 10;
for (int i = 0; i < passLen; i++) {

使代码生成10个字符

Makes the code generate 10 characters

cout << (char) (rand() % ('z' - '0' + 1) + '0');

是实际工作.
我想你了解的东西.
rand()生成一个新的随机数.
%Modulus运算符-有效地将随机数限制在零到第二个参数减一之间.
``z''-``0''+ 1第二个参数设置字符范围的上限.
+"0"将结果转换为可打印的ASCII字符-随机数为0,然后为"0",如果为1,则为"1",如果为9,则为"9" ',如果是十个则为':'-参见此处 http://www.asciitable.com/ [ ^ ]中的Ascii字符,您将明白我的意思.

第二个参数只是说我希望我的结果在"0"和"z"之间,所以给我值即差值加1"-因为一个值将被模运算丢弃.如果它是从"0"到"9",那么它将是57-48 + 1,(显然)是10-因此,随机数将是0到9(含0和9).

Does teh actual work.
The cout stuff I assume you understand.
rand() generates a new random number.
% Modulus operator - effectively limits the random number to between zero and the second parameter minus one.
''z'' - ''0'' + 1 The second parameter, sets upper limit of the range of characters.
+ ''0'' Converts the result to a printable ASCII character - it the random number is 0, then ''0'', if it is one, the ''1'', if it is nine then ''9'', if it is ten then '':'' - see here http://www.asciitable.com/[^] for the Ascii characters and you will see what I mean.

The second parameter is just saying "I want my results to be between ''0'' and ''z'', so give me value that is the difference plus one" - because the one will be discarded by the modulus operation. if it was ''0'' to ''9'' then it would be 57 - 48 + 1 which is (obviously) 10 - so teh random number would be 0 to 9 inclusive.


这篇关于生成伪随机数/大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆