首頁  >  文章  >  後端開發  >  C程式計算等差數列的第N項

C程式計算等差數列的第N項

WBOY
WBOY轉載
2023-09-01 14:09:07879瀏覽

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
..<p>APn = a1 + (n-1) *</p>

#所以公式將是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項
  • 傳回上述計算得到的Output 。
##演算法

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</p><p>", n, nth_ap(a,d,n));
   return 0;
}

輸出

The 5th term of the series is: 6

以上是C程式計算等差數列的第N項的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除