首页 > 解决方案 > 在 C 中显示二维数组中的随机字符串

问题描述

我正在用 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++)
    {
        puts(compliment[i]);
    }
    return 0;
}

这个程序的输出是:

You look so beautiful!
You are a great person!
Your hair is so stunning!

但我希望随机显示赞美,而不是全部显示。我怎样才能做到这一点?我应该使用哪个功能?

编辑:感谢您的评论。我做的:

#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;
}

标签: carrays

解决方案


首先,我们可以在 C 中使用 Shuffle 数组中shuffle()的函数

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>

而在main()

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]]);
}

推荐阅读