2015-01-21 132 views
-5

我有一个数字10,我想乘以每个数减去1的数字它就像这样:如何在C#中将每个数字乘以1减去1?

10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

然后结果。 如何在C#中处理这个问题?

+2

你想共同计算[因子](http://stackoverflow.com/questions/16583665/for-loop-to-calculate-factorials)。 – 2015-01-21 09:04:12

+1

'while(mul!= 0)result * = mul - 'or such ... – 2015-01-21 09:04:26

+0

在Math中称为[Factorial](http://en.wikipedia.org/wiki/Factorial)。此Google [搜索](https://www.google.com.tr/search?q=c%23+calculate+factorial)返回134.000结果。一探究竟。 – 2015-01-21 09:05:41

回答

3

这是一个简单的阶乘函数。您可以使用递归方法:

unsigned int Factorial(unsigned int val) 
{ 
    return (1 == val)? 1 : Factorial(val - 1); 
} 

或迭代方法:

unsigned int Factorial(unsigned int val) 
{ 
    unsigned int result = val; 
    while(1 < --val) 
    { 
     result *= val; 
    } 
    return result; 
} 

注意,它不会对大的输入值的工作,因为德因子会很快溢出的整数。

+1

为什么'返回结果-1'? – 2015-01-21 09:10:18

+0

@PeterSchneider因为在喝咖啡之前我无法打字。 :-) 感谢您指出了这一点。修复。 – 2015-01-21 09:12:05

+0

@TimSchmelter - 析因(50)返回-3258495067890909184 – fubo 2015-01-21 09:38:30

-1

试试这个 -

 var res = 1; 
     for (int num = 10; num > 0; num--) 
      res += res * (num - 1); 

     MessageBox.Show(res.ToString()); 
+0

尽管OP说的有点不清楚,我会假设这个例子显示了他想要的东西,即计算阶乘。在这种情况下,你的一个班轮只是第一步。 – 2015-01-21 09:15:33

+0

OP问清楚如何计算[阶乘](http://en.wikipedia.org/wiki/Factorial)。样本说明了一切。 – 2015-01-21 09:21:02

+0

谢谢你们纠正我..更新了答案。 – Rohit 2015-01-21 09:34:18

相关问题