C#阶乘计算器工作不正常
本文关键字:不正常 工作 计算器 阶乘 | 更新日期: 2023-09-27 18:25:35
我的阶乘计算器工作不太正常。
正如我的教授所希望的那样,它在1点到20点之间正常工作。但是,输入0应该返回1的阶乘;它返回0
这是我的代码:
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");
}
以下是调用上述方法的方法,即计算按钮的事件处理程序:
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
想法?
如果您在调试器中逐步解决这个问题,问题就会变得非常明显。由于您刚刚开始编程,我强烈建议尽早使用调试器。这是一个绝对宝贵的编程工具。
看看你的for
循环:
for (int i = 1; i < number; i++)
当number
是0
时会发生什么?循环从不运行。不能将0
包含在循环范围中,因为这将通过首先将每个结果乘以0
来将其设置为0
。因此,您需要在函数逻辑中添加对0
的显式检查:
if (number == 0)
return 1;
// continue with your loop here
根据定义,0的阶乘是1,而不是计算,您的代码不会反映这一点。在代码前添加一个检查:
if (number == 0)
result = 1;
else
// compute factorial
还可以考虑创建一个返回整数值作为结果的函数。
您可以使用这个:
if(number == 0){
result = 1;
}
for (int i = 1; i <= number; i++)
result *= i;
}
您的公式也是错误的,因为n! = 1*2*3*.....*n
您可以测试以下代码!测试并工作。递归实现和基本实现
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;
}
}
}
}