简体   繁体   English

C#阶乘计算器无法正常工作

[英]C# factorial calculator is not working right

My factorial calculator isn't working quite correctly. 我的阶乘计算器无法正常工作。

It works as expected from 1 to 20, as my professor wants. 正如我的教授所希望的,它在1到20的范围内正常工作。 However, entering 0 should return a factorial of 1; 但是,输入0应该返回阶乘1;否则输入0。 it returns 0 它返回0

Here is my code: 这是我的代码:

        private void CalculateFactorial(long number)
    {
        //perform the calculations
        long result = number;
        for (int i = 1; i < number; i++)
        {
            result = result * i;
        }

        //display the calculated Factorial to the user
        txt_Factorial.Text = result.ToString("n0");
    }

Here is the method which calls the above method, the event handler for the calculate button: 这是调用上述方法的方法,即calculate按钮的事件处理程序:

private void btn_Calculate_Click(object sender, EventArgs e)
    {
        //get the users input
        long number = long.Parse(txt_Number.Text);

        // make sure the number not invalid. If it is invalid, tell the user
        // otherwise, proceed to calculation. 
        if (number < 0 || number > 20)
            txt_Factorial.Text = "Invalid Number";
        else
            CalculateFactorial(number);
        txt_Number.Focus(); // returns the focus to the number box whether or not data was valid

Ideas? 有想法吗?

If you step through this in a debugger the problem becomes pretty clear. 如果您在调试器中逐步解决此问题,那么问题将变得很明显。 And as you're just getting started with programming I highly recommend getting used to a debugger as early as you can. 而且,当您刚刚开始编程时,我强烈建议您尽早习惯调试器。 It's an absolutely invaluable tool for programming. 它是编程的绝对宝贵工具。

Look at your for loop: 查看您的for循环:

for (int i = 1; i < number; i++)

What happens when number is 0 ? number0怎样? The loop never runs. 循环永远不会运行。 You can't include 0 in the loop range because that would set every result to 0 by first multiplying it by 0 . 您不能在循环范围内包含0 ,因为那样会先将结果乘以0 ,然后将每个结果都设置为0 So you need to add an explicit check for 0 in the function logic: 因此,您需要在函数逻辑中添加对0的显式检查:

if (number == 0)
    return 1;
// continue with your loop here

Factorial of 0 is 1 by definition, not by calculation, and your code does not reflect that. 根据定义(而不是通过计算),阶乘0为1,并且您的代码不反映这一点。 Add a check before your code: 在代码之前添加支票:

if (number == 0)
    result = 1;
else 
    // compute factorial

Also think about creating a function that returns an integer value as the result. 还要考虑创建一个返回整数值作为结果的函数。

You can use this : 您可以使用:

if(number == 0){
    result = 1;
}
for (int i = 1; i <= number; i++)
    result *=  i;
}

also your formula is wrong because n! = 1*2*3*.....*n 您的公式也是错误的,因为n! = 1*2*3*.....*n n! = 1*2*3*.....*n

You can test the following code! 您可以测试以下代码! tested and works. 测试和工作。 Recursive Implementation as well as basic implementation 递归实施以及基本实施

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication50
{
    class Program
    {
        static void Main(string[] args)
        {

        NumberManipulator manipulator = new NumberManipulator();
        Console.WriteLine("Please Enter Factorial Number:");
        int a= Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("---Basic Calling--");
        Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));

        Console.WriteLine("--Recursively Calling--");
        Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));

        Console.ReadLine();
    }
}

class NumberManipulator
{
    public int factorial(int num)
    {
        int result=1;
        int b = 1;
        do
        {
            result = result * b;
            Console.WriteLine(result);
            b++;
        } while (num >= b);
        return result;
    }

    public int recursively(int num)
    {
        if (num <= 1)
        {
            return 1;
        }
        else
        {
            return recursively(num - 1) * num;
        }
    }
  }
}

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

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