用来计算算术级数的 C++ 程序
提供 "a"(首项)、"d"(公差)和 "n"(序列中的值的数量),任务是生成序列,并进而计算其和。
什么是等差数列
等差数列是具有公差的数列,其中该数列的首项是固定的 "a",而它们之间的公差是 "d"。
表示如下 −
a, a + d, a + 2d, a + 3d, . . .
示例
Input-: a = 1.5, d = 0.5, n=10 Output-: sum of series A.P is : 37.5 Input : a = 2.5, d = 1.5, n = 20 Output : sum of series A.P is : 335
以下使用的做法如下 −
- 以首项 (a)、公差 (d) 和序列中的项数 (n) 作为数据输入
- 遍历循环直到 n,并用差值继续向临时变量添加首项
- 打印生成的结果
算法
Start Step 1-> declare Function to find sum of series float sum(float a, float d, int n) set float sum = 0 Loop For int i=0 and i<n and i++ Set sum = sum + a Set a = a + d End return sum Step 2-> In main() Set int n = 10 Set float a = 1.5, d = 0.5 Call sum(a, d, n) Stop
示例
#include<bits/stdc++.h>
using namespace std;
// Function to find sum of series.
float sum(float a, float d, int n) {
float sum = 0;
for (int i=0;i<n;i++) {
sum = sum + a;
a = a + d;
}
return sum;
}
int main() {
int n = 10;
float a = 1.5, d = 0.5;
cout<<"sum of series A.P is : "<<sum(a, d, n);
return 0;
}输出
sum of series A.P is : 37.5
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP