自定义一个函数求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
时间: 2023-11-17 15:08:05 浏览: 151
您可以自定义一个函数来求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
```
阅读全文