用C语言编写设s=1/2+1/3+……+1/n,求与8最接近的s值
时间: 2024-06-13 22:08:07 浏览: 96
以下是用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
```
相关问题
设s=1/2+1/3+……+1/n,求与8最接近的s值用C语言编写
以下是用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
```
阅读全文