C語言幾何級數第N項程式
給定首項為 'a',公比為 'r',級數項數為 'n'。任務是找到該級數的第 n 項。
因此,在討論如何為該問題編寫程式之前,我們應該首先了解什麼是幾何級數。
數學中的幾何級數或幾何序列是指除首項外的每一項都是透過將前一項乘以一個公比得到的,且項數固定。
例如,2、4、8、16、32...是一個幾何級數,首項為 2,公比為 2。如果 n = 4,則輸出將為 16。
因此,我們可以說幾何級數的第 n 項將類似於 -
GP1 = a1 GP2 = a1 * r^(2-1) GP3 = a1 * r^(3-1) . . . GPn = a1 * r^(n-1)
因此公式將為 GP = a * r^(n-1)。
示例
Input: A=1 R=2 N=5 Output: The 5th term of the series is: 16 Explanation: The terms will be 1, 2, 4, 8, 16 so the output will be 16 Input: A=1 R=2 N=8 Output: The 8th Term of the series is: 128
**我們將用於解決給定問題的方案** -
- 獲取首項 A、公比 R 和級數項數 N。
- 然後透過 A * (int)(pow(R, N - 1) 計算第 n 項。
- 返回上述計算得到的輸出。
演算法
Start Step 1 -> In function int Nth_of_GP(int a, int r, int n) Return( a * (int)(pow(r, n - 1)) Step 2 -> In function int main() Declare and set a = 1 Declare and set r = 2 Declare and set n = 8 Print The output returned from calling the function Nth_of_GP(a, r, n) Stop
示例
#include <stdio.h>
#include <math.h>
//function to return the nth term of GP
int Nth_of_GP(int a, int r, int n) {
// the Nth term will be
return( a * (int)(pow(r, n - 1)) );
}
//Main Block
int main() {
// initial number
int a = 1;
// Common ratio
int r = 2;
// N th term to be find
int n = 8;
printf("The %dth term of the series is: %d
",n, Nth_of_GP(a, r, n) );
return 0;
}輸出
The 8th term of the series is: 128
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP