C 库函数 - rand()

C 语言教程 · 2019-02-24 10:59:07

描述

C 库函数 int rand(void) 返回一个范围在 0 到 RAND_MAX 之间的伪随机数。

RAND_MAX 是一个常量,它的默认值在不同的实现中会有所不同,但是值至少是 32767。

声明

下面是 rand() 函数的声明。

int rand(void)

参数

  • NA

返回值

该函数返回一个范围在 0 到 RAND_MAX 之间的整数值。

实例

下面的实例演示了 rand() 函数的用法。

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

int main()
{
   int i, n;
   time_t t;
   
   n = 5;
   
   /* 初始化随机数发生器 */
   srand((unsigned) time(&t));

   /* 输出 0 到 49 之间的 5 个随机数 */
   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }
   
  return(0);
}

让我们编译并运行上面的程序,这将产生以下结果:

38
45
29
29
47

点击查看所有 C 语言教程 文章: https://www.codercto.com/courses/l/17.html

查看所有标签

Complexity and Approximation

Complexity and Approximation

G. Ausiello、P. Crescenzi、V. Kann、Marchetti-sp、Giorgio Gambosi、Alberto M. Spaccamela / Springer / 2003-02 / USD 74.95

This book is an up-to-date documentation of the state of the art in combinatorial optimization, presenting approximate solutions of virtually all relevant classes of NP-hard optimization problems. The......一起来看看 《Complexity and Approximation》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码