首先,让我们讨论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