c++ - 带阶乘方程的概率计算器

标签 c++ probability factorial

我必须编写一个代码,根据可供选择的号码数量和必须选择的号码来计算中奖概率。我必须在代码中使用阶乘方程 (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/

相关文章:

c++ - Gnu make:生成所有子目录的列表

c++ - 在 MSVC++14 上的 C++11 中难以置信的快速委托(delegate)

python - scikit-learn (sklearn) 中 GaussianMixture 的负 BIC 值

algorithm - 求阶乘 n 模 m 比 O(n) 更快

c - 用户输入的因素问题

c++ - 哪些脚本语言可用于 msxml4.dll xsl 转换?

java - 选择具有特定范围的唯一随机数

algorithm - 布隆过滤器中的过滤器索引和哈希函数

prolog - Prolog中的逆阶乘

c++ - 带有 roi 的 opencv 错误断言