C 编程中从单词列表中生成随机单词
嘿,我想问我是否有一个单词列表,比如“老虎、狮子、大象、斑马、马、骆驼、鹿、鳄鱼、兔子、猫” 我怎样才能在c编程中从列表中随机生成5个单词? 例如:
老虎,斑马,猫,鹿,马
或
鳄鱼,兔子,骆驼,斑马,大象
等
提前谢谢你:D
编辑:
#include <stdio.h>
#include <string.h>
#define SIZE 10
int main ()
{
char arr2[SIZE][20] = { "tiger", "lion", "elephant", "zebra", "horse", "camel", "deer", "crocodile", "rabbit", "cat" };
int x = 0;
srand(time(NULL));
while (x < SIZE - 5)
{
arr2 [x][20] = rand ();
printf ("%s\n", arr2[x]);
x++;
}
system ("pause");
return 0;
}
hey, i wanna ask if i have a list of words let say 'tiger, lion, elephant, zebra, horse, camel, deer, crocodile, rabbit, cat'
haw can i generate 5 words out of the list randomly in c programming?
for example:
tiger, zebra, cat, deer, horse
or
crocodile, rabbit, camel, zebra, elephant
ect
thank you in advance :D
Edit:
#include <stdio.h>
#include <string.h>
#define SIZE 10
int main ()
{
char arr2[SIZE][20] = { "tiger", "lion", "elephant", "zebra", "horse", "camel", "deer", "crocodile", "rabbit", "cat" };
int x = 0;
srand(time(NULL));
while (x < SIZE - 5)
{
arr2 [x][20] = rand ();
printf ("%s\n", arr2[x]);
x++;
}
system ("pause");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将单词放入数组中。生成 5 个(或其他)在正确范围 (0..array_size-1) 内的伪随机数。使用这些数字从数组中挑选单词。
Put the words into an array. Generate 5 (or whatever) pseudo-random numbers in the right range (0..array_size-1). Use those numbers to pick words from the array.
您可以执行以下操作:
k
并且可以像这样访问数组元素arr2[k]
。rand
函数来完成,您可能已经调用过该函数,但方式错误。check[SIZE] = {0,}
并在打印arr2[k]
之前,检查是否check[k]==0
,然后打印该值。打印后设置arr2[k]=1
。完成这些后,请粘贴您的代码。希望您能理解这个问题的逻辑。
You can do the following:
k
and you can access the array elements like thisarr2[k]
.rand
function which you have probably called but in a wrong waycheck[SIZE] = {0,}
and before printingarr2[k]
, check ifcheck[k]==0
and then print the value. After printing setarr2[k]=1
.Once you are done with this much please paste your code. Hope you will understand the logic to this problem.
出于说明目的,这是 C#,但我确信您可以相当容易地转换为 C:
For illustrative purposes, this is C# but I'm sure you can convert to C, fairly easily: