使用c++ 编写计算阶乘的函数。在主程序中调用该函数计算s=m!+n!+k!的和。其中,m、n、k的值从键盘输入。
时间: 2024-05-11 22:13:43 浏览: 10
```c
#include <stdio.h>
int factorial(int n) { // 计算阶乘的函数
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int m, n, k, s;
printf("请输入m、n、k的值:");
scanf("%d%d%d", &m, &n, &k);
s = factorial(m) + factorial(n) + factorial(k); // 调用计算阶乘的函数
printf("%d! + %d! + %d! = %d\n", m, n, k, s);
return 0;
}
```
相关问题
用C++计算s = 1!+2!+3!+…+n!的源程序,书写阶乘函数,并调用上面式子
以下是用C++计算s = 1!+2!+3!+…+n!的源程序:
```cpp
#include <iostream>
using namespace std;
int factorial(int n) {
int f = 1;
if (n < 0) {
cout << "你输入的数据有误!" << endl;
} else {
for (int i = 1; i <= n; i++) {
f *= i;
}
}
return f;
}
int main() {
int n, s = 0;
cout << "输入一个数:" << endl;
cin >> n;
for (int i = 1; i <= n; i++) {
s += factorial(i);
}
cout << "s = " << s << endl;
return 0;
}
```
2.c++写 计算s = 1!+2!+3!+…+n!的源程序,书写阶乘函数,并调用求上面式子
以下是C++计算s = 1!+2!+3!+…+n!的源程序,包括阶乘函数的书写和调用:
```c++
#include <iostream>
using namespace std;
int factorial(int n) { // 阶乘函数
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n, s = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
s += factorial(i); // 累加每个数的阶乘
}
cout << s << endl;
return 0;
}
```