gpt4 book ai didi

c - 如何在 C 中将随机大写字母数组填充为函数?

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:32 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来用 40 个随机大写字母填充一个数组。我试图填充数组并打印它,但没有得到任何输出。

提前致谢。

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

void fillS1(char y[]);

int main(int argc, const char * argv[])
{
char s1[40];
int n;

fillS1(&s1[40]);

for (n = 0; n < 41; n++) {
printf("%s", s1);
}


return 0;
}

void fillS1(char y[40]){

int x = 1;

while (x < 41) {
x = rand() % 26;
x = 2 + 'A';
x = y[x];
x++;
}


}

最佳答案

我只会写代码

void fill_string_40(char str[])
{
for (int i=0; i<40; i++)
str[i] = 'A' + random() % 26;
str[40] = (char)0; // (char)0 is equal to use '\0'
}

并将其用作(例如在您的 main 中)

{ char s[41];
fill_string_40(s);
printf("%s\n", s);
}

请注意,您需要一个额外的字节作为空终止字符。我们假设一些 ASCII 兼容的字符编码。一种更便携的方式可能是

str[i] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random() % 26];

因为文字字符串是字符的常量数组。

如果您使用 C++ 编写代码,请参阅 standard <random> header file .如果您为 Linux 编写代码,请参阅 random(4)getrandom(2) , 也许与 srandom(3) 一起使用.另请阅读 Mersenne Twister

关于c - 如何在 C 中将随机大写字母数组填充为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12907865/

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