我需要从1到9的随机数(不含0).
//numbers 0 to 9
int iRand = rand() % 10;
Run Code Online (Sandbox Code Playgroud)
但我需要1到9岁.
谢谢.
好吧,你知道如何获得[0,x]范围内的随机整数,对吧?那是:
rand() % (x + 1)
Run Code Online (Sandbox Code Playgroud)
在你的情况下,你已经将x设置为9,给你rand() % 10.那你如何操纵范围达到1-9呢?好吧,因为0是这个随机数生成器方案的最小值,我们知道我们需要添加一个至少有一个:
rand() % (x + 1) + 1
Run Code Online (Sandbox Code Playgroud)
现在你得到范围[1,x + 1].如果假设是[1,9],则x必须为8,给出:
rand() % 9 + 1
Run Code Online (Sandbox Code Playgroud)
这就是你应该如何思考这些事情.