编写程序求1!+2!+3!+ …+n!
时间: 2023-11-24 10:52:12 浏览: 80
以下是使用Java编写程序求1!+2!+3!+ …+n!的例子:
```java
import java.util.Scanner;
public class FactorialSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数n:");
int n = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
System.out.println("1!+2!+3!+...+n!的和为:" + sum);
}
public static int factorial(int num) {
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
}
```
相关问题
编写程序求1!+2!+3!+..+n!
以下是C语言编写程序求1!+2!+3!+..+n!的例子:
```c
#include <stdio.h>
int main()
{
int n, i, j, sum = 0, s = 1;
scanf("%d", &n); // 输入n
for (i = 1; i <= n; i++) {
s = 1; // 每次循环前将s初始化为1
for (j = 1; j <= i; j++) {
s = s * j; // 计算i的阶乘
}
sum = sum + s; // 累加阶乘之和
}
printf("%d", sum); // 输出结果
return 0;
}
```
采用调用自定义函数的形式编写程序 求1!+2!+3!+4!+…+n!
```c
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int i, n;
long sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
sum += factorial(i);
}
printf("The sum of factorials from 1 to %d is: %ld\n", n, sum);
return 0;
}
```
阅读全文