输入一个正整数,计算1!+2!+n!
时间: 2023-12-21 18:15:19 浏览: 88
请问您需要什么语言的代码呢?以下为Python、Java和C++的代码:
Python代码:
n = int(input("请输入一个正整数:"))
factorial = 1
sum = 0
for i in range(1, n+1):
factorial *= i
sum += factorial
print("1! + 2! + ... + n! =", sum)
Java代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int n = input.nextInt();
int factorial = 1;
int sum = 0;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
System.out.println("1! + 2! + ... + n! = " + sum);
}
}
C++代码:
#include <iostream>
using namespace std;
int main() {
int n, factorial = 1, sum = 0;
cout << "请输入一个正整数:" << endl;
cin >> n;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
cout << "1! + 2! + ... + n! = " << sum << endl;
return 0;
}
阅读全文