求s=s1的值是=1+1/2+1/3+...1/n
时间: 2024-01-29 20:04:41 浏览: 132
求1+1/2+1/3+1/4+…….+1/100的值
求s=s1的值是=1+1/2+1/3+...1/n的方法有两种:
1. 使用for循环计算:
```c
#include <stdio.h>
float fun(int n){
int i;
float s = 0.0;
for(i = 1; i <= n; i++){
s = s + 1.0 / i;
}
return s;
}
int main(){
int n;
float s;
printf("Please enter N:");
scanf("%d", &n);
s = fun(n);
printf("the result is: %f\n", s);
return 0;
}
```
2. 使用while循环计算:
```c
#include <stdio.h>
float fun(int n){
int i = 1;
float s = 0.0;
while(i <= n){
s = s + 1.0 / i;
i++;
}
return s;
}
int main(){
int n;
float s;
printf("Please enter N:");
scanf("%d", &n);
s = fun(n);
printf("the result is: %f\n", s);
return 0;
}
```
阅读全文