C ++程序生成给定数字范围的随机序列
首先,让我们讨论rand()函数。rand()函数是C++的预定义方法。在<stdlib.h>头文件中声明。rand()用于生成范围内的随机数。这里min_n是随机数的最小范围,而max_n是随机数的最大范围。因此,rand()将返回min_n到(max_n–1)之间的随机数,包括极限值。在这里,如果我们将下限和上限分别称为1和100,则rand()将返回从1到(100–1)的值。即从1到99。
算法
Begin
Declare max_n to the integer datatype.
Initialize max_n = 100.
Declare min_n to the integer datatype.
Initialize min_n = 1.
Declare new_n to the integer datatype.
Declare i of integer datatype.
Print “The random number is:”.
for (i = 0; i < 10; i++)
new_n = ((rand() % (max_n + 1 - min_n)) + min_n)
Print the value of new_n.
End.示例
#include <iostream>#include <stdlib.h>using namespace std;int main() { int max_n = 100; int min_n = 1; int new_n; int i; cout<<"The random number is: \n"; for (i = 0; i < 10; i++) { new_n = ((rand() % (max_n + 1 - min_n)) + min_n); //rand() returns random decimal number. cout<<new_n<<endl; } return 0;}输出结果
The random number is: 42 68 35 1 70 25 79 59 63 65
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短