gpt4 book ai didi

c - 随 secret 码生成器相同的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:26 26 4
gpt4 key购买 nike

这是我的第一个 C 程序,我想随机生成一个密码,但每次运行该程序时,它都会生成相同的字符串。 (总是生成“pkDHTxmMR1 ...”)这实际上不会被使用,所以 rand() 的安全性对我来说并不重要。为什么每次运行它都会输出相同的字符串?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//this is a program to generate a random password

int main()
{
int counter = 0;
srand(time(NULL));
char randChar;

int passwordLength;

printf("Type in a password Length \n");
scanf("%d", &passwordLength);

while(counter < passwordLength)
{
//seed random based on time
srand(time(NULL));
randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
printf("%c", randChar);
counter++;
}
return 0;
}

最佳答案

亲爱的。每个人都答错了,包括在我自己尝试提问者的代码之前的我。

事实上,是的,在循环中不应该调用 srand(),因为它会在每次迭代时重新播种随机数生成器。但是,也不应在循环外调用 srand(),因为用于生成实际随机数的函数是 random() 而不是 rand() 。正确的代码是

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
int counter = 0;
srandom(time(NULL)); // Correct seeding function for random()
char randChar;

int passwordLength;

printf("Type in a password Length \n");
scanf("%d", &passwordLength);

while(counter < passwordLength)
{
randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
printf("%c", randChar);
counter++;
}
printf("\n"); // Stops the output from being on the same line as the prompt
return 0;
}

关于c - 随 secret 码生成器相同的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30486336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com