我必须编写一个代码,根据可供选择的号码数量和必须选择的号码来计算中奖概率。我必须在代码中使用阶乘方程 (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;
}
最佳答案
在阶乘运算的意义上,C++ 中没有 ! 运算符,并且您的 factorial
函数不计算阶乘。 (! 运算符通常是逻辑NOT 运算符。)
这就是写阶乘方法的方式,
int factorial(int n) {
return (n <= 1 ? 1 : n * factorial(n - 1));
}
该方法是递归的并且对整数进行操作 - 您可能需要考虑这是否适合您的任务
那么您的原始函数应该重命名为 double choice(int n, int k)
并使用新的 factorial
实现。
关于c++ - 带阶乘方程的概率计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21790644/