n阶乘的程序怎么写

时间:2025-01-28 11:36:04 单机游戏

C语言

方法一:使用for循环

```c

include

int factorial(int n) {

int result = 1;

for (int i = 1; i <= n; i++) {

result *= i;

}

return result;

}

int main() {

int n;

printf("请输入一个正整数n:");

scanf("%d", &n);

printf("%d的阶乘为:%d\n", n, factorial(n));

return 0;

}

```

方法二:使用while循环

```c

include

int factorial(int n) {

int result = 1;

int i = 1;

while (i <= n) {

result *= i;

i++;

}

return result;

}

int main() {

int n;

printf("请输入一个正整数n:");

scanf("%d", &n);

printf("%d的阶乘为:%d\n", n, factorial(n));

return 0;

}

```

方法三:使用递归

```c

include

long factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

}

}

int main() {

int n;

printf("请输入一个正整数n:");

scanf("%d", &n);

printf("%d的阶乘为:%ld\n", n, factorial(n));

return 0;

}

```

Python

```python

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

n = int(input("请输入一个整数n: "))

print(f"{n}的阶乘是:{factorial(n)}")

```

Java

```java

public class Factorial {

public static long factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

}

}

public static void main(String[] args) {

int n = 5; // 可以修改输入的数字

System.out.println(n + "的阶乘是:" + factorial(n));

}

}

```

C++

```cpp

include

unsigned long long factorial(int n) {

unsigned long long result = 1;

for (int i = 1; i <= n; i++) {

result *= i;

}

return result;

}

int main() {

int n;

std::cout << "请输入一个正整数n:";

std::cin >> n;

std::cout<< n << "的阶乘为:" << factorial(n) << std::endl;

return 0;

}

```

这些示例展示了如何使用不同的编程语言和方法(包括循环和递归)来计算n的阶乘。你可以根据自己的需求和编程环境选择合适的实现方式。