在C中显示2D数组中的随机字符串
我正在用C语言编写一个随机恭维生成器程序在C中显示2D数组中的随机字符串,c,arrays,C,Arrays,我正在用C语言编写一个随机恭维生成器程序 #include <stdio.h> int main() { int i; char compliment[3][30] = {"You look so beautiful!", "You are a great person!", "Your hair is so stunning!"}; for(i=0;i<sizeof(compliment)/sizeof(compliment[0]);i++)
#include <stdio.h>
int main()
{
int i;
char compliment[3][30] = {"You look so beautiful!", "You are a great person!", "Your hair is so stunning!"};
for(i=0;i<sizeof(compliment)/sizeof(compliment[0]);i++)
{
puts(compliment[i]);
}
return 0;
}
但我希望这些赞美是随机的,只是其中一个,而不是全部。我该怎么做?我应该使用哪个函数
编辑:
谢谢你的评论。我做到了:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i;
char compliment[3][30] = {"You look so beautiful!", "You are a great person!", "Your hair is so stunning!"};
srand(time(NULL));
puts(compliment[rand() % 3]);
return 0;
}
#包括
#包括
#包括
int main()
{
int i;
char恭维[3][30]={“你看起来真漂亮!”,“你是一个伟大的人!”,“你的头发真漂亮!”;
srand(时间(空));
put(恭维[rand()%3]);
返回0;
}
首先,我们可以使用
查找
rand()
函数以生成一个随机索引。一次生成一个索引意味着什么?如果要随机选取其中一条消息,请删除行的,并使用put(恭维[rand()%3])
不要忘记使用srand(time(NULL))设置种子代码>从一开始。谢谢。我现在正在阅读有关它的内容。看来这就是我需要的!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i;
char compliment[3][30] = {"You look so beautiful!", "You are a great person!", "Your hair is so stunning!"};
srand(time(NULL));
puts(compliment[rand() % 3]);
return 0;
}
void shuffle(int *array, size_t n)
{
if (n > 1)
{
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
#include <time.h>
int i;
char compliment[3][30] = {"You look so beautiful!", "You are a great person!", "Your hair is so stunning!"};
const int size = sizeof(compliment)/sizeof(compliment[0]);
srand(clock()); // set random seed
int a[size];
for(i=0 ; i<size ; i++) a[i] = i;
shuffle(a, size);
for(i=0;i<size;i++)
{
puts(compliment[a[i]]);
}