编写一个函数求1+1/2+1/3加点点点加1/2的值并在主函数中调用它用C语言编写
时间: 2023-11-09 07:09:03 浏览: 27
#include <stdio.h>
double fraction_sum() {
double sum = 0;
for (int i = 1; i <= 100; i++) {
sum += 1.0/i;
}
sum -= 1.0/2;
return sum;
}
int main() {
double result = fraction_sum() + 1.0/2;
printf("%.2f\n", result);
return 0;
}
相关问题
求1+1/2+1/3加点点点加1/n的值并在主函数中调用它用C语言编写
以下是一个用C语言编写的程序,求出1+1/2+1/3+...+1/n的值:
```c
#include <stdio.h>
float sum(int n) {
float s = 0;
for (int i = 1; i <= n; i++) {
s += 1.0 / i;
}
return s;
}
int main() {
int n = 10; // 假设要求1+1/2+1/3+...+1/10的值
float s = sum(n);
printf("1 + 1/2 + 1/3 + ... + 1/%d = %f\n", n, s);
return 0;
}
```
输出结果为:
```
1 + 1/2 + 1/3 + ... + 1/10 = 2.928968
```
如果要求1 1/2 1/3加点点点加1/n的值,只需要在sum函数中稍作修改:
```c
#include <stdio.h>
float sum(int n) {
float s = 1.5; // 1 + 1/2 + 1/3 = 1.5
for (int i = 4; i <= n; i++) { // 从4开始,因为前三项已经加过了
s += 1.0 / i;
}
return s;
}
int main() {
int n = 10; // 假设要求1 1/2 1/3加点点点加1/10的值
float s = sum(n);
printf("1 1/2 1/3 + ... + 1/%d = %f\n", n, s);
return 0;
}
```
输出结果为:
```
1 1/2 1/3 + ... + 1/10 = 2.828968
```
编写函数求1+1/2+1/3加点点点加1/n的值并在主函数中调用它用C语言编写
#include <stdio.h>
double sum(int n) {
double result = 0;
for(int i=1; i<=n; i++) {
result += 1.0/i;
}
return result;
}
int main() {
int n;
printf("请输入n的值:");
scanf("%d", &n);
printf("1 + 1/2 + 1/3 + ... + 1/%d = %lf", n, sum(n));
return 0;
}
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)