循环语句的阶乘

本文关键字:阶乘 语句 循环 | 更新日期: 2023-09-27 17:56:05

我无法让这个 for 循环执行它应该执行的阶乘。它似乎只循环一次。

 static void Main(string[] args)
    {
    int a;
    int total=1;
    Console.WriteLine("Please enter any number");
    a = Convert.ToInt32 (Console.ReadLine());
    total = a;
        for (int intcount = a; intcount<= 1; intcount--)
          {
            total *= intcount;    
        }
        Console.WriteLine("Factorial of number '{0}' is '{1}'", a, total);
        Console.ReadKey();

循环语句的阶乘

intcount<= 1

一旦你开始循环,这是错误的,所以循环会立即退出。

您可能希望在该数字大于 1 时进行循环。

您应该

将初始化从total = a更改为total = 1intcount<= 1将初始化更改为intcount > 1,如下所示:

var a = 5;
var total = 1;
for (int intcount = a; intcount > 1; intcount--)
{
     total *= intcount;    
}
Console.WriteLine (total);//prints 120
total = 0;
for (int intcount = 1; intcount<= a; intcount++)
{
   total *= intcount;    
}

total = a;
for (int intcount = a; intcount>= 1; intcount--)
  {
    total *= intcount;    
}

大于 1 时循环:

for (int intcount = a; intcount > 1; intcount--) {
  total *= intcount;
}

或者,循环到以下值:

for (int intcount = 2; intcount <= a; intcount++) {
  total *= intcount;
}

完整的解决方案就在这里! 经过测试并工作。递归实现以及基本实现

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;
        }
    }
  }
}