C語言程式:算術級數的第N項


給定首項'a',公差'd'和項數'n'。任務是找到該級數的第n項。

因此,在討論如何編寫解決此問題的程式之前,我們首先應該瞭解什麼是算術級數。

算術級數或算術序列是一個數字序列,其中兩個連續項之間的差是相同的。

例如,我們有首項a=5,公差為1,我們想找到的第n項為3。所以,這個序列將是:5, 6, 7,所以輸出必須是7。

因此,我們可以說算術級數的第n項將類似於:

AP1 = a1
AP2 = a1 + (2-1) * d
AP3 = a1 + (3-1) * d
..

APn = a1 + (n-1) *

所以公式將是 AP = a + (n-1) * d。

示例

Input: a=2, d=1, n=5
Output: 6
Explanation: The series will be:
2, 3, 4, 5, 6 nth term will be 6
Input: a=7, d=2, n=3
Output: 11

我們將用來解決給定問題的方案

  • 取首項A,公差D和項數N。
  • 然後透過 (A + (N - 1) * D) 計算第n項
  • 返回上述計算得到的輸出。

演算法

Start
   Step 1 -> In function int nth_ap(int a, int d, int n)
      Return (a + (n - 1) * d)
   Step 2 -> int main()
      Declare and initialize the inputs a=2, d=1, n=5
      Print The result obtained from calling the function nth_ap(a,d,n)
Stop

示例

#include <stdio.h>
int nth_ap(int a, int d, int n) {
   // using formula to find the
   // Nth term t(n) = a(1) + (n-1)*d
   return (a + (n - 1) * d);
}
//main function
int main() {
   // starting number
   int a = 2;
   // Common difference
   int d = 1;
   // N th term to be find
   int n = 5;
   printf("The %dth term of AP :%d
", n, nth_ap(a,d,n));    return 0; }

輸出

The 5th term of the series is: 6

更新於:2019年11月20日

8K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告