编写一个 C 语言程序,使用数学公式和不使用数学公式查找等比数列(G.P. Series)的和。
等比数列
等比数列是指一个序列,其中下一个元素是通过将公比乘以前一个元素得到的。或者说,等比数列是这样一种数字序列,其中任何连续数字(项)的公比始终相同。
等比数列和背后的数学公式
Sn = a(rn) / (1- r)
Tn = ar(n-1)
C 语言查找等比数列和的程序示例
该程序允许用户输入首项、项数和公比。然后,它将找到等比数列的和。这里,我们使用了 For 循环 来显示 G.P. 数列,这是可选的。
/* Program to find Sum of Geometric Progression Series */
#include <stdio.h>
#include<math.h>
int main() {
int a, n, r;
float tn, sum = 0;
printf(" Please Enter First Number of an G.P Series: ");
scanf("%d", &a);
printf(" Please Enter the Total Numbers in this G.P Series: ");
scanf("%d", &n);
printf(" Please Enter the Common Ratio: ");
scanf("%d", &r);
sum = (a * (1 - pow(r, n ))) / (1- r);
tn = a * (pow(r, n - 1));
printf("\n The Sum of Geometric Progression Series = %.2f", sum);
printf("\n The tn Term of Geometric Progression Series = %.2f \n", tn);
return 0;
}
Please Enter First Number of an G.P Series: 1
Please Enter the Total Numbers in this G.P Series: 5
Please Enter the Common Ratio: 2
The Sum of Geometric Progression Series = 31.00
The tn Term of Geometric Progression Series = 16.00
在此 程序 中,我们没有使用任何数学公式。
/* Program to find Sum of Geometric Progression Series */
#include <stdio.h>
#include<math.h>
int main() {
int a, n, r, value, i;
float sum = 0;
printf(" Please Enter First Number of an G.P Series: ");
scanf("%d", &a);
printf(" Please Enter the Total Numbers in this G.P Series: ");
scanf("%d", &n);
printf(" Please Enter the Common Ratio: ");
scanf("%d", &r);
value = a;
printf("G.P Series : ");
for(i = 0; i < n; i++)
{
printf("%d ", value);
sum = sum + value;
value = value * r;
}
printf("\n The Sum of Geometric Progression Series = %f\n", sum);
return 0;
}
Please Enter First Number of an G.P Series: 2
Please Enter the Total Numbers in this G.P Series: 5
Please Enter the Common Ratio: 2
G.P Series : 2 4 8 16 32
The Sum of Geometric Progression Series = 62.000000
C 语言使用函数计算等比数列和的程序
这个等比数列 C 程序 与上面的相同。但是,我们使用 函数 将 C 编程 逻辑分开了。
/* Program to find Sum of Geometric Progression Series */
#include <stdio.h>
#include<math.h>
int sumofGP(int a, int n, int r)
{
int sum = (a * (1 - pow(r, n))) / (1- r);
return sum;
}
int main() {
int a, n, r;
float sum = 0;
printf(" Please Enter First Number of an G.P Series: ");
scanf("%d", &a);
printf(" Please Enter the Total Numbers in this G.P Series: ");
scanf("%d", &n);
printf(" Please Enter the Common Ratio: ");
scanf("%d", &r);
sum = sumofGP(a, n, r);
printf("\n The Sum of Geometric Progression Series = %f\n", sum);
return 0;
}
