繁体   English   中英

使用阶乘函数法组合

[英]Combination by using factorial function method

我不能将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实现不是很正确,但是我将把它作为练习找出原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM