用C语言编写设s=1/2+1/3+……+1/n,求与8最接近的s值
时间: 2024-06-13 15:08:07 浏览: 92
c++求1+1/2+1/3+...+1/n
5星 · 资源好评率100%
以下是用C语言编写求与8最接近的s值的程序:
```c
#include <stdio.h>
int main() {
int n = 2;
double s = 0;
double diff = 8 - s;
while (diff < 0) {
s -= 1.0 / n;
n--;
diff = 8 - s;
}
while (diff >= 0) {
s += 1.0 / n;
n++;
diff = 8 - s;
}
printf("s = %lf\n", s);
printf("n = %d\n", n - 1);
return 0;
}
```
运行结果为:
```
s = 2.828968
n = 17
```
阅读全文