21xrx.com
2024-04-20 00:44:56 Saturday
登录
文章检索 我的文章 写文章
C语言生成随机数
2021-07-07 10:10:34 深夜i     --     --
C

使用 rand 和随机函数生成伪随机数的 C 程序(仅限 Turbo C 编译器)。 由于随机数是由函数中使用的算法生成的,因此它们是伪随机的,这就是使用单词 pseudo 的原因。 函数 rand() 返回一个介于 0 和 RAND_MAX 之间的伪随机数。 RAND_MAX 是一个与平台相关的常量,它等于 rand 函数返回的最大值。

 

使用 rand 的 C 编程代码

我们在程序中使用模数运算符。 如果您计算 a % b 其中 a 和 b 是整数,那么对于 a 和 b 的任何一组值,结果将始终小于 b。 例如对于 a = 1243 和 b = 100a % b = 1243 % 100 = 43对于 a = 99 和 b = 100a % b = 99 % 100 = 99对于 a = 1000 和 b = 100a % b = 1000 = % 1

在我们的程序中,我们打印范围为 [0, 100] 的伪随机数。 所以我们计算 rand() % 100 它将返回一个 [0, 99] 中的数字,所以我们加 1 以获得所需的范围。
 

#include <stdio.h>
#include <stdlib.h>


int main() {
  int c, n;

  printf("Ten random numbers in [1,100]\n");

  for (c = 1; c <= 10; c++) {
    n = rand() % 100 + 1;
    printf("%d\n", n);
  }

  return 0;
}

 

如果您重新运行此程序,您将获得相同的一组数字。 每次都可以使用不同的数字:srand(unsigned int seed) 函数; 这里的种子是一个无符号整数。 因此,每次运行程序时,您都需要不同的种子值,因为您可以使用始终不同的当前时间,因此您将获得一组不同的数字。 默认情况下,如果不使用 srand 函数,则种子 = 1。

使用随机函数的 C 编程代码(仅限 Turbo C 编译器)

函数 randomize 用于初始化随机数生成器。 如果不使用它,那么每次运行程序时都会得到相同的随机数。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>


int main()
{
   int n, max, num, c;

   printf("Enter the number of random numbers you want\n");
   scanf("%d", &n);

   printf("Enter the maximum value of random number\n");
   scanf("%d", &max);

   printf("%d random numbers from 0 to %d are:\n", n, max);
   
   randomize();

   for (c = 1; c <= n; c++)
   {
      num = random(max);
      printf("%d\n",num);        
   }

   getch();
   return 0;
}

 

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章