使用js Math.random()函數產生n到m間的隨機數字,jsmath.random

來源:互聯網
上載者:User

使用js Math.random()函數產生n到m間的隨機數字,jsmath.random

摘要:

本文講解如何使用js產生n到m間的隨機數字,主要目的是為後期的js產生驗證碼做準備。

Math.random()函數返回0和1之間的偽隨機數,可能為0,但總是小於1,[0,1)

產生n-m,包含n但不包含m的整數:

第一步算出 m-n的值,假設等於w

第二步Math.random()*w

第三步Math.random()*w+n

第四步parseInt(Math.random()*w+n, 10)

產生n-m,不包含n但包含m的整數:​

第一步算出 m-n的值,假設等於w

第二步Math.random()*w

第三步Math.random()*w+n

第四步Math.floor(Math.random()*w+n) + 1

產生n-m,不包含n和m的整數:

第一步算出 m-n-2的值,假設等於w

第二步Math.random()*w

第三步Math.random()*w+n +1

第四步Math.round(Math.random()*w+n+1) 或者 Math.ceil(Math.random()*w+n+1)

產生n-m,包含n和m的隨機數:

第一步算出 m-n的值,假設等於w

第二步Math.random()*w

第三步Math.random()*w+n

第四步Math.round(Math.random()*w+n) 或者 Math.ceil(Math.random()*w+n)

例子:

  產生800-1500的隨機整數,包含800但不包含1500

複製代碼 代碼如下:
1500-800 = 700
Math.random()*700
var num = Math.random()*700 + 800;
num = parseInt(num, 10);

只需要簡單的四步就可以完成。

補充:

  Math.ceil() 返回大於等於數字參數的最小整數(取整函數),對數字進行上舍入

  Math.floor() 返回小於等於數字參數的最大整數,對數字進行下舍入

  Math.round() 返回數字最接近的整數,四捨五入


用C函數怎產生m到n之間的偽隨機數

msdn上現成的例子。
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void SimpleRandDemo( int n )//簡單得產生n個隨機數
{
// Print n random numbers.
int i;
for( i = 0; i < n; i++ )
printf( " %6d\n", rand() );
}

void RangedRandDemo( int range_min, int range_max, int n )//產生range_min到range_max之間的n個隨機數
{
// Generate random numbers in the half-closed interval
// [range_min, range_max). In other words,
// range_min <= random number < range_max
int i;
for ( i = 0; i < n; i++ )
{
int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)
+ range_min;
printf( " %6d\n", u);
}
}

int main( void )
{
// Seed the random-number generator with the current time so that
// the numbers will be different every time we run.
srand( (unsigned)time( NULL ) );

SimpleRandDemo( 10 );
printf("\n");
RangedRandDemo( -100, 100, 10 );
}
 
使用math對象的random方法隨機產生一個100~999之間的隨機整數並把十位以上的數字取出Javascript

function random_num(){
var num = Math.random() * 999;
if(num < 100){

random_num();

}else{
return num; //隨機出來的數字

}

}

var _num = random_num();
var baiwei = _num % 100; //十位
var shiwei = (_num - baiwei) % 10; //百位
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.