c - 在 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;
}
解决方案
首先,我们可以在 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]]);
}
推荐阅读
- amazon-web-services - 如何更改 AWS SSO 中的默认目录别名?
- sql - 如何使 SQL 请求 COUNT DISTINCT 有条件?
- java - Spring Boot如何在更新前检查数据库中的编码密码是否与表单中的密码匹配
- java - 如何获得犹太历的一年中的一周
- user-interface - Jupyter 交互式小部件未正确执行
- python - Keras -“节点”对象没有属性“输出掩码”
- python - 当前方法和类名进入日志记录;这些方法在功能上是否等效?
- python - 检查字符串是否包含数字、字母和空格
- html - th:each - 在同一列中设置所有属性?
- android - recyclerView 添加和删除