c - How can i pick a number from an array in C?
问题描述
Basically i made an array with number 1,2,3.
int array[3] = {1,2,3};
How can I select a random number from this list and assign it to a different variable?
解决方案
Use the rand()
function and mod the result down to 3 values 0, 1, or 2 using mod. Then access the corresponding value in your array:
srand(time(NULL));// without this rand() function might continuously give the same value
int index = rand() % 3;
printf("random: %d\n", array[index]);
Considering that the array contains hardcoded values, you could simply:
int i = (rand() % 3) + 1;
printf("random: %d\m", i);
Include the header file <stdio.h>
, <time.h>
, <stdlib.h>
推荐阅读
- visual-studio-code - VS Code 中许多与光标词相关的命令有什么区别?
- python - 无法在 TensorFlow 中使用 GPU 进行训练
- azure - Azure AppGW:路由到特定的 URL 路径
- java - Spring Boot Kafka 健康检查不起作用
- python - 删除 Pandas 数据框中不需要的 str
- python - 系列驱动的多个条件
- java - resteasy:@QueryParam 解析嵌套数组结构
- php - 使用 RSA 公钥解密
- r - R - 如何在从网站抓取 pdf 时跳过错误的 url 以避免重新运行抓取任务?
- typescript - @ManyToOne 没有反向 - 属性没有出现在 find 中