从C中的数组随机元素

编程入门 行业动态 更新时间:2024-10-25 08:21:57
本文介绍了从C中的数组随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何可以选择在C字符数组随机元素?

How can I select a random element from a character array in c ?

例如:

char *array[19]; array[0] = "Hi"; array[1] = "Hello";

我要寻找像数组[兰德],其中RAND是O和数组的长度之间的随机整数(在本例中20),如1,2,3,19等。

I am looking for something like array[rand], where rand is the random integer number between o and the array's length(in this case 20) like 1, 2, 3 , 19 etc.

推荐答案

要开始做事了,因为你有一个字符串数组的不是字符,您必须将其申报为的char *数组[ 19];

To start things off, since you have an array of strings, not of characters, you have to declare it as char* array[19];

然后,您可以声明如下(总是有用)宏

Then, you can declare the following (always useful) macro

的#define ARR_SIZE(ARR)(sizeof的((ARR))/ sizeof的((ARR [0])))

最后,你可以选择改编[兰特()%ARR_SIZE(ARR)] (同​​时牢记执行%在兰特()为不可以的正确方法做的范围内得到一个随机数。

Last, you can choose arr[rand() % ARR_SIZE(arr)] (while keeping in mind that performing % on rand() is not the proper way to do get a random number within a range.

更多推荐

从C中的数组随机元素

本文发布于:2023-11-29 00:22:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644550.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!