我必須做一個代碼,計算中獎彩票的概率,給定的數量可供選擇的數量以及您必須選擇多少。我必須在代碼中使用階乘方程(n!)/(k!*(n-k)!)
。代碼本身工作正常,但公式不會編譯。概率計算器與階乘方程
//This program calculates the probability of winning the lottery
#include <iostream>
using namespace std;
double factorial(int n, int k);
int main()
{
//variables
int n;
int k;
char pa;
int chance;
double prob;
//loop
do
{
cout << "How many numbers (1-12) are there to pick from?\n" << endl;
cin >> n;
if(n>12 || n<1)
{
cout << "Invalid entry.\nHow many numbers (1-12) are there to pick from?\n";
cin >> n;
}
cout << "How many numbers must you pick to play?\n";
cin >> k;
if(k>n || k<1)
{
cout << "Invalid entry.\nHow many numbers must you pick to play?\n";
cin >> n;
}
cout << "Your chance of winning the lottery is 1 in " << chance << endl;
prob=factorial(n, k);
cout << "This is a probability of " << prob << endl;
cout << "Play again?";
cin >> pa;
} while (pa != 'n');
return 0;
}
double factorial(int n, int k)
{
double fact;
fact=(n!)/(k!*(n-k)!);
return fact;
}
即使您的代碼確實有效,您的函數「factorial」甚至不計算該因子。寫一個計算n的函數階乘!並在另一個函數內使用它來計算概率。你在'factorial'函數中的公式會計算一個二項式係數(如果編譯的話) – mathematician1975
非C代碼...去除標籤。 – crashmstr