C#阶乘计算
示例
一个数字的阶乘(用!表示,例如9!)是该数字与一个低阶阶乘的乘积。因此,例如9!=9x8!=9x8x7!=9x8x7x6x5x4x3x2x1。
因此,在使用递归的代码中:
long Factorial(long x) { if (x < 1) { throw new OutOfRangeException("阶乘只能与正数一起使用。"); } if (x == 1) { return 1; } else { return x * Factorial(x - 1); } }
一个数字的阶乘(用!表示,例如9!)是该数字与一个低阶阶乘的乘积。因此,例如9!=9x8!=9x8x7!=9x8x7x6x5x4x3x2x1。
因此,在使用递归的代码中:
long Factorial(long x) { if (x < 1) { throw new OutOfRangeException("阶乘只能与正数一起使用。"); } if (x == 1) { return 1; } else { return x * Factorial(x - 1); } }