2013-01-24 113 views
0

我無法得到這個循環來執行它所應該的因子。它似乎只是循環一次。循環語句的因子

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
intcount<= 1 

這是錯誤的,只要你開始你的循環,因此該循環立即退出。

你可能想循環,而這個數字是大於1

0

你應該改變從total = a初始化total = 1intcount<= 1intcount > 1這樣的:

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

工作!非常感謝。只是學習。 – user2008260

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

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

循環而值是比1:

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

另外,環達價值:

for (int intcount = 2; intcount <= a; intcount++) { 
    total *= intcount; 
} 
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; 
     } 
    } 
    } 
}