我想从 26 个字母中随机选择单词(有或无意义)。该单词包含 6 个字母,允许字母重复。
如何使用 C(或 Objective C)程序来完成此操作?如果有任何想法,我将非常感激。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
srand(time(NULL));
for (int i = 0; i < 6; ++i)
{
putchar('a' + (rand() % 26));
}
putchar('\n');
return EXIT_SUCCESS;
}
加盐调味。
OP似乎不知道如何编译上面的内容。如果保存到名为
so.c
的文件中,请使用同一文件夹中的 make so CFLAGS=-std=c99
进行编译。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Written by kaizer.se */
void randword(char *buf, size_t len)
{
char alphabet[] = "abcdefghijklmnopqrstuvxyz";
size_t i;
for (i = 0; i < len; i++) {
size_t idx = ((float)rand()/RAND_MAX) * (sizeof(alphabet) -1);
buf[i] = alphabet[idx];
}
buf[len] = '\0';
}
int main(void) {
char buf[1024];
srand(time(NULL));
randword(buf, 7);
printf("Word: %s\n", buf);
return 0;
}
测试:
$ ./rword
Word: xoilfvv