C++中擲N次骰子後點數的最大值
任務是計算擲N次M面的骰子後可以預期的點數最大值。
骰子的第一個麵包含1個點,第二個麵包含2個點,以此類推。同樣,第M個麵包含M個點。
每個面出現的機率為1/M。
讓我們用一個例子來理解我們要做什麼:
輸入 - M=2, N=3
輸出 - 1.875
解釋 - 骰子有2個面 = {1, 2}
如果擲骰子3次,則樣本空間將為 = MN = 23
{(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2,)
(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2,)}
Maximum number in (1, 1, 1) = 1
Maximum number in (1, 1, 2) = 2
Maximum number in (1, 2, 1) = 2
Maximum number in (1, 2, 2) = 2
Maximum number in (2, 1, 1) = 2
Maximum number in (2, 1, 2) = 2
Maximum number in (2, 2, 1) = 2
Maximum number in (2, 2, 2) = 2
Probability of each case = 1/23 = 0.125
Therefore, expectation of maximum number = (1+2+2+2+2+2+2+2) * (0.125) = 1.875輸入 - M=2, N=2
輸出 - 1.75
下面程式中使用的演算法如下:
可以使用公式iN – (i-1)N透過其前一個數字找到某個數字可能出現的最大情況數。
例如,如果M=4且N=2,則最大值為4的情況總數為42 – (4-1)2 = 7。
因此,最終答案將是對從1到M的每個元素應用此公式:
(i * (iN – (i - 1)N )) / MN 並將它們加起來。
在MaxExpect()函式中,初始化一個double型別的變數max = 0來儲存總和。
然後從i=M迴圈到i>0
在迴圈內部應用上述公式,並將所有結果值新增到變數max中。
示例
#include <bits/stdc++.h>
using namespace std;
double MaxExpect(double M, double N){
double max = 0.0, i;
for (i = M; i; i--)
/*formula to find maximum number and
sum of maximum numbers*/
max += (pow(i / M, N) - pow((i - 1) / M, N)) * i;
return max;
}
int main(){
double M = 2, N = 3;
cout << MaxExpect(M, N);
return 0;
}輸出
如果我們執行上面的程式碼,我們將得到以下輸出:
1.875
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP