C语言求s=1+1/2+1/3+1/4+…+1/100
时间: 2023-11-06 21:05:24 浏览: 67
这个问题可以使用循环来解决,具体代码如下:
```c
#include <stdio.h>
int main() {
double s = 0;
for (int i = 1; i <= 100; i++) {
s += 1.0 / i;
}
printf("s = %lf\n", s);
return 0;
}
```
输出结果为:s = 5.187378
相关问题
用C语言求S=1+1/2+1/3 +1/100
以下是用C语言求S=1+1/2+1/3+...+1/100的代码:
```c
#include <stdio.h>
int main() {
double sum = 0;
for (int i = 1; i <= 100; i++) {
sum += 1.0 / i;
}
printf("S = %lf", sum);
return 0;
}
```
输出结果为:S = 5.187378
c语言设计s=1+1/2+1/3+…+1/n
以下是两种C语言设计s=1+1/2+1/3+…+1/n的例子:
1.使用for循环计算
```c
#include <stdio.h>
int main(void) {
int n = 0;
float sum = 1;
printf("请输入n: ");
scanf("%d", &n);
for (int i = 2; i <= n; i++) {
sum += 1.0 / i;
}
printf("1+1/2+1/3+...+1/%d=%f\n", n, sum);
return 0;
}
```
2.使用函数计算
```c
#include <stdio.h>
#include <stdlib.h>
int fac(int n) //阶乘函数
{
int i = 0;
int y = 1; //用来存返回值
if (0 == n || 1 == n) {
return 1;
} else {
for (i = 2; i <= n; i++) {
y *= i;
}
return y;
}
}
double sum(int n) //求和函数
{
int i = 0; //循环变量
double sum = 0; //和
for (i = 1; i <= n; i++) {
sum += 1.0 / fac(i);
}
return sum;
}
int main() {
int n = 0;
printf("请输入n: ");
scanf("%d", &n);
printf("sum = %lf\n", sum(n));
system("pause"); return 0;
}
```
相关推荐
![](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)