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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP