首页  >  文章  >  后端开发  >  C程序计算等差数列的第N项

C程序计算等差数列的第N项

WBOY
WBOY转载
2023-09-01 14:09:07877浏览

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 项
  • 返回输出通过以上计算得到。

算法

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删除