使用阶乘函数法进行组合

本文关键字:组合 函数 阶乘 | 更新日期: 2023-09-27 18:35:04

>我不能将 20 和 17 组合在一起,程序说结果是 1。为什么??我确定我的代码是正确的,但我只是无法组合大数字。

using System;
namespace question
{
    class beat_That
    {
        static int Factorial(int m)
        {
            int result = 1;
            for (int i = 1; i <= m; i++)
            {
                result *= i;
            }
            return result;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("enter number of objects in the set: ");
            int n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("enter number to be chosen: ");
            int k = Convert.ToInt32(Console.ReadLine());
            int combination = Factorial(n) / (Factorial(n - k) * Factorial(k));
            Console.WriteLine("C(" + n + ", " + k + ") = " + combination);
            Console.ReadKey();
        }
    }
}

使用阶乘函数法进行组合

我猜这是家庭作业?以下是一些提示,希望能让您朝着正确的方向前进:

(1(通常,.NET类是Pascal Case,因此例如:comb应该是Comb。 此外,最好分配描述性类名而不是简短的缩写。为了清楚起见,我将假设您至少将comb重命名为 Comb,这样它就不会与变量名称混淆,但例如,可能会Calculator另一个选项。

(2( 检查语法和任何编译器错误。例如,编译器应该抱怨这行代码: Console.WriteLine("the combination of {0} and {1} is {2}. "),a1,b1,;

(3( 您的方法FactorialCombinationstatic方法(与实例方法相对(。这将更改调用这些方法的方式。 调用静态方法时没有实例,例如:Comb.Combination(..)

(4( 确保测试各种输入!您对Combination的实现并不完全正确,但我会将其作为找出原因的练习。