2016-11-10 114 views
1

我想要在1到3之間的C++中產生10個隨機數,這樣1會出現最多時間(比如50%),然後是2(30%),然後是3( 20%)。是否有可能這樣做?生成具有一定概率的隨機數

我已經提出了下面的代碼來獲得1和3之間的隨機數字,但我將如何添加概率?

#include <iostream> 
#include <windows.h> 
#include "time.h" 
int main(int argc, char*argv[]) 
{ 
    srand (time(NULL)); 
    for (int t = 0; t < 10; t++) 
    { 
     int random_x; 

     random_x = rand() % 3+1; 
     std::cout << "\nRandom X = " << random_x << std::endl; 
    } 
    Sleep(50000); 
    return 0; 
} 
+1

您可以查看內置發行版[此處](http://en.cppreference.com/w/cpp/numeric/random) – NathanOliver

回答

-1

你可以做這樣的事情(在僞代碼)

x=random(0,100) 
if(x<p1){ 
    y=1; 
} else if (x<p2) 
    y=2 
} else{ 
    y=3 
} 

p1爲1
P2-P1的變化2
和100-P2的變化是改變for 3