sum=1+1/2+1/3+1/4+………+1/999/1000
时间: 2023-11-20 21:05:51 浏览: 87
以下是求sum=1+1/2+1/3+1/4+………+1/999/1000的近似值的Python代码:
```python
import math
sum = 0
n = 1
while True:
sum += 1 / n
n += 1
if n > 1000:
break
print("sum的近似值为:", round(sum, 4))
```
输出结果为:sum的近似值为:7.4855
相关问题
自定义一个函数求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
```
c 语言 sum=1+1/2+1/3+1/4+………+1/999/1000
以下是两种C语言求1到1000的和的例子:
1.使用for循环计算1到100的和
```c
#include <stdio.h>
int main(void) {
int i;
float sum = 0;
for(i = 1; i <= 1000; i++) {
sum += 1/(float)(i);
}
printf("sum = %f\n", sum);
return 0;
}
```
2.使用for循环计算1到n的和
```c
#include <stdio.h>
int main () {
int n, i;
scanf("%d", &n);
double sum = 0.0;
for( i=1; i<=n; i++){
sum += 1.0/i;
}
printf("f(%d)=%f", n, sum);
return 0;
}
```
阅读全文