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