如何在1到20之间获得10个数字? [英] How do I get 10 number between 1 to 20?

查看:170
本文介绍了如何在1到20之间获得10个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我想知道如何得到10个随机数,但是在1到20之间,每次10个没有。应该是不同的。

喜欢2,8,11,14,4,7,9,18,14,20

这个数字不应该重复

并将值存储在数组中[]



我尝试过:



我尝试了rand命令,但是它给了我一个随机数,而不是1到20之间的数字,我无法存储它

Hey, I want to know how to get 10 random number but between 1 to 20 and every time that 10 no. Should be different.
Like 2,8,11,14,4,7,9,18,14,20
The number should not repeat
And store the value in array[ ]

What I have tried:

I tried the rand command but it gives me a random number not number between 1 to 20 and I can't store it

推荐答案

来电1到20之间的随机数只需使用解决方案#1



但是......让它重复安全...



To call the random number between 1 and 20 just use the solution #1

But... to make it repetition safe...

0) Create an empty result_array for your 10 result numbers
1) Fill one check_array[20] with numbers from 1 to 20 to track what has been used

2) within a loop until you get the 10 random numbers without repetition
   2.1) call the random function of solution #1
   2.2) check if the number has been already used (is this number still in the array of (1)?)
      2.2.1) If yes... save the random number to the next empty position of your results array and put a "0" in that check_array's position
      2.2.2) if not... start 2 again

   2.3) if you already have all 10 non-repeated numbers... end loop

3) Print out your results


正如所建议的直接解决方案Grame_Grant ,使用 C ++ 标准库的强大功能: random_shuffle - C ++参考 [ ^ ] 。



另一方面,如果你想自己实现算法,那么我在这里描述一下: ^ ]。
A direct solution is, as already suggested by Grame_Grant, using the power of the C++ standard library: random_shuffle - C++ Reference[^].

On the other end if you want to implement yourself the algorithm, then I describe it here: Random extraction of 5 cards from a deck[^].


另一种[创意]解决方案是随机改组一组数字。这样就不会有重复...;)



Google搜索有多种不同的方式: c ++ random shuffle array [ ^ ]
An alternative [creative] solution is to randomly shuffle a set of numbers. This way there will be no repeats... ;)

This Google Search has many different ways of doing it: c++ random shuffle array[^]


这篇关于如何在1到20之间获得10个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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