S=1+1/2!+1/3!+……+1/+n!,C++
时间: 2023-12-07 21:38:39 浏览: 38
以下是C++代码实现S=1+1/2!+1/3!+……+1/+n!:
```c++
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
int n;
double sum=0;
double fac=1;
cin>>n;
for(int i=1;i<=n;i++)
{
fac*=i;
sum+=1/fac;
}
printf("%.3lf",sum+1);
return 0;
}
```
相关问题
c++编程计算S=1+1/3+1/5+……+1/99
```c++
#include <iostream>
using namespace std;
int main() {
float s = 0;
for (int i = 1; i <= 99; i += 2) {
s += 1.0 / i;
}
cout << s << endl;
return 0;
}
// 输出结果为:1.56904
```
--相关问题--:
1. 如何计算S=1+1/2+1/3+……+1/n?
2
自定义一个函数求1+1/2+1/3+……+1/n,编写程序,在主函数中求s=s1+s2+s3的值,其中: s1=1+1/2+1/3+……+1/5 s2=1+1/2+1/3+……+1/10 s3=1+1/2+1/3+……+1/20
您可以自定义一个函数来求1+1/2+1/3+……+1/n,代码如下:
```c++
double sum(int n) {
double res = 0;
for (int i = 1; i <= n; i++) {
res += 1.0 / i;
}
return res;
}
```
然后在主函数中,您可以调用这个函数来求s1、s2、s3的值,代码如下:
```c++
#include <iostream>
using namespace std;
double sum(int n);
int main() {
double s1 = sum(5);
double s2 = sum(10);
double s3 = sum(20);
double s = s1 + s2 + s3;
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s = " << s << endl;
return 0;
}
double sum(int n) {
double res = 0;
for (int i = 1; i <= n; i++) {
res += 1.0 / i;
}
return res;
}
```
输出结果为:
```
s1 = 2.28333
s2 = 2.92897
s3 = 3.59774
s = 8.81004
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)