因子循环语句

时间:2013-01-24 16:44:46

标签: c# factorial

我不能让这个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();

5 个答案:

答案 0 :(得分:5)

intcount<= 1

一旦开始循环,这就是假,所以循环立即退出。

您可能想要循环,而该数字更多而不是1。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

当值大于而不是1时循环

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

或者,循环到值:

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

答案 4 :(得分:0)

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

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