用來計算算術級數的 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