[英]rand() producing the same results even after srand()
Currently I'm trying to write just a simple program to generate a string of random characters to represent a name. 目前,我正在尝试编写一个简单的程序来生成一串随机字符来表示一个名称。 Calling it once produces what I want, however if I call the function again to make the last name, I get the same result as the first name, length and everything. 一次调用它会产生我想要的东西,但是,如果再次调用该函数来命名,我得到的结果将与名字,长度和所有内容相同。 I currently seed rand at the top with time(), so I'm not sure what's wrong/what I can do. 我目前在time()的顶部将rand用作种子,所以我不确定这是什么错误/我能做什么。 Any help would be appreciated, thanks for your time. 任何帮助将不胜感激,谢谢您的时间。
My code is as follows: 我的代码如下:
int main(void)
{
srand(time(NULL));
int randomNum = 0;
char firstName[12] = { 0 };
char lastName[36] = { 0 };
char fullName[50] = { 0 };
/*for (int j = 0; j < 20; j++)
{
*/ randomNum = rand() % 10 + 2;
strcpy(firstName, generateName(randomNum));
printf("First: %s\n", firstName);
randomNum = rand() % 34 + 2;
strcpy(lastName, generateName(randomNum));
printf("Last: %s\n\n", firstName);
//strcat(fullName, firstName);
//strcat(fullName, " ");
//strcat(fullName, lastName);
//}
//getchar();
return 0;
}
And the generateName function is as follows: 而generateName函数如下:
char* generateName(int length)
{
char* randomName = NULL;
randomName = (char*)malloc(sizeof(char) * (length + 1));
if (randomName)
{
randomName[0] = rand() % 26 + 65;
for (int i = 1; i < length; i++)
{
randomName[i] = rand() % 26 + 97;
}
randomName[length] = '\0';
}
return randomName;
}
Again, thanks for your time. 再次感谢您的宝贵时间。
I think you generate the last name all right, but when you print it: 我认为您可以生成姓氏,但是在打印时:
printf("Last: %s\n\n", firstName);
^here
See? 看到? You are printing the first name again!! 您将再次打印名字!!
Just do: 做就是了:
printf("Last: %s\n\n", lastName);
PS: The best thing about VisualStudio is its integrated debugger. PS:关于VisualStudio最好的是它的集成调试器。 You should learn to use it, and these kind of errors will show themselves. 您应该学习使用它,这些错误会自行显示。
You are printing firstName in the second print statement in stead of lastName :D Otherwise your code is fine - produces a new name in each run. 您将在第二个打印语句中代替firstName:D来打印firstName,否则您的代码就可以了-在每次运行中都产生一个新名称。
printf("Last: %s\\n\\n", firstName); printf(“ Last:%s \\ n \\ n”,firstName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.