詳解C語言中rand函數的使用_C 語言

來源:互聯網
上載者:User

前言

我們在編程實現演算法的過程中,往往需要使用到隨機數。由於電腦是一台以邏輯為基礎的機器,沒法做到真正的隨機(大概量子電腦可以?)。所以電腦產生的是偽隨機數,供我們使用。

我們使用C語言的rand函數,產生的也是偽隨機數。

c語言之rand函數的使用

1、寫入標頭檔

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

2、變數的定義

void main( void ) { int i,k;

3、srand( (unsigned)time( NULL ) ); /*選取種子檔案*/

4、for( i = 0; i <20;i++ ) /*迴圈控制20個隨機數的產生*/ { k=rand()%100; /*儲存隨機數*/ printf( ” k=%d\n”, k ); /*輸出隨機數*/ } }

      1、此為隨機函數的一種產生方法

      2、如果只需一個,那麼可以省略迴圈控制

一個簡單的示範如下:

#include <stdio.h>#include <stdlib.h>#include <time.h>intmain(int argc, char** argv){  // 以機器當前的時間來構造產生偽隨機數的"種子" 。   srand((unsigned int)time(NULL));  int i;  // 列印10個偽隨機數   for (i = 0; i < 10; i++) {        printf("%d ", rand());  }  printf("\n");    system("pause");  return 0;}

總結

以上就是關於C語言中rand函數的使用的全部內容,希望本文對大家日常使用C語言的時候能有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.