如何使用rand()在一个范围内生成数字?(复制)

时间:2021-12-17 03:25:26

Possible Duplicate:
Generate Random numbers uniformly over entire range
How to use rand function to

可能的重复:在整个范围内均匀地生成随机数如何使用rand函数

Could anyone tell me how to use the rand() function in C programming with 1 = min and
7 = max, 1 and 7 included.

谁能告诉我如何在C编程中使用rand()函数,其中包括1 = min和7 = max, 1和7。

Thanks

谢谢

2 个解决方案

#1


15  

This will do what you want:

这将做你想做的:

rand() % 7 + 1

Explanation:

解释:

  • rand() returns a random number between 0 and a large number.

    rand()返回一个0到一个大数字之间的随机数。

  • % 7 gets the remainder after dividing by 7, which will be an integer from 0 to 6 inclusive.

    % 7在除以7后得到余数,这是一个从0到6的整数。

  • + 1 changes the range to 1 to 7 inclusive.

    + 1将范围更改为1到7(含)。

#2


3  

Use the modulo operator. It returns the remainder when dividing. Generate a number in range 0 to 6 by using rand() % 7. Add 1 to that to generate a number in range 1 to 7.

使用的模运算符。它在除法时返回余数。使用rand() % 7生成范围为0到6的数字。再加1,生成范围为1到7的数字。

#1


15  

This will do what you want:

这将做你想做的:

rand() % 7 + 1

Explanation:

解释:

  • rand() returns a random number between 0 and a large number.

    rand()返回一个0到一个大数字之间的随机数。

  • % 7 gets the remainder after dividing by 7, which will be an integer from 0 to 6 inclusive.

    % 7在除以7后得到余数,这是一个从0到6的整数。

  • + 1 changes the range to 1 to 7 inclusive.

    + 1将范围更改为1到7(含)。

#2


3  

Use the modulo operator. It returns the remainder when dividing. Generate a number in range 0 to 6 by using rand() % 7. Add 1 to that to generate a number in range 1 to 7.

使用的模运算符。它在除法时返回余数。使用rand() % 7生成范围为0到6的数字。再加1,生成范围为1到7的数字。