编写函数,求级数S=1+2+3+...n,并在主函数中求: y= (1+2+3)+(1+2+3+4)+(1+2+3+4+5)/ (1+2+3+4+5+6)+(1+2+3+4+5+6+7)
时间: 2024-05-23 18:07:45 浏览: 16
编写函数求级数S=1+2+3+...n的方法如下:
```c++
int sum(int n){
int s = 0;
for(int i = 1; i <= n; i++){
s += i;
}
return s;
}
```
其中,sum是函数名称,n是函数的参数,表示要求前n项的和。函数内部通过循环求和得到结果,并将结果返回。
接下来,在主函数中求y=(1+2+3)+(1+2+3+4)+(1+2+3+4+5)/(1+2+3+4+5+6)+(1+2+3+4+5+6+7)的值,可以按照以下代码实现:
```c++
#include <iostream>
using namespace std;
int sum(int n);
int main() {
int y = sum(3) + sum(4) + sum(5);
int denominator = sum(6) + sum(7);
double result = (double)y / denominator;
cout << "y = " << y << endl;
cout << "denominator = " << denominator << endl;
cout << "y / denominator = " << result << endl;
return 0;
}
int sum(int n){
int s = 0;
for(int i = 1; i <= n; i++){
s += i;
}
return s;
}
```
其中,sum函数与之前介绍的一样,主函数中先计算分子的值y,然后计算分母的值denominator,并将两者相除得到结果result。最后输出y、denominator和result的值。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)