rand()函数,用于在给定的一组数字中生成一个随机数 [英] rand() function, to genetare a random number within the given set of numbers

查看:109
本文介绍了rand()函数,用于在给定的一组数字中生成一个随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我是一名c ++初学者。我在c ++中遇到了关于rand函数的这个问题。它希望我们编写一个代码,该代码从给定的一组数字中生成一个随机数。我有关于rand()函数的关注,但没有关于它的这个功能!!我已经用Google搜索了!!但还没有找到令人满意的解决方案。请帮帮我。

hello,
i am a c++ beginner. i came across this question regarding rand function in c++. it wants us to program a code which generates a random number from a given set of numbers. i have herd about the rand() function but not about this feature regarding it!! i have already googled it!! but have not found a satisfying solution. please help me.

推荐答案

你可以在这里使用几种方法:

蛮力和无知方法是使用rand生成一个随机数,该rand位于有效集中的最大和最小数字之间。如果该数字在集合中,请使用它。如果不是,则生成另一个号码并再次检查。这有效,但是......它很慢,可能需要无限的时间来生成一个新的数字。



最好的方法是设置一个包含有效数字集的数组,并使用rand生成一个介于0和项目数(减1)之间的数字,然后使用该数字作为索引从数组中选择一个数字。每次尝试时,这将花费相同的时间来选择一个数字。它可以扩展为从集合中删除数字,因此也不会重复 - 这就是智能音乐播放器播放曲目的方式,或者洗牌一包卡片的方式。
There are a couple of approaches you could use here:
The Brute-Force-And-Ignorance approach is to generate a random number using rand which is between the largest and smallest numbers in the valid set. If this number is in the set, use it. If it isn't, then generate another number and check again. This works, but...it's very slow, and may take an infinite time to generate a new number.

The best way to do it is to set up an array containing the set of valid numbers, and generate a number which is between zero and the number of items (minus one) using rand, and then use that number as an index to select a number from the array. This will take the same amount of time to select a number every time you try. And it can be extended to remove the number from the set so there are never duplicates, either - this is the way "intelligent" music players shuffle tracks for example, or the way to "shuffle" a pack of cards.


我假设数字是一组给定的数字。然后尝试用..

I assume numbers is a set of given numbers.Then have a try with..
int numbers[] = { 3, 13, 22, 57, 417 };
int length = sizeof(numbers) / sizeof(int);
int randomNumber = numbers[rand() % length];


我google和这个 [ ^ ]是列表的首位。
I googled and this[^] was top of the list.


这篇关于rand()函数,用于在给定的一组数字中生成一个随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆