计算几何级数的C程序
问题
编写一个程序,读取两个数字x和n,然后计算几何级数的和。
1+x+x2+x3+x4+……….+xn
然后,打印x、n和sum。
解决方案
以下是使用C编程语言计算几何级数的解决方案:
算法
参考计算几何级数的算法。
步骤1 - 开始
步骤2 - 重复
步骤3 - 在运行时读取x和n的值
步骤4 - 如果n > 0,则
步骤4.1: 对于 i = 0 到 n 执行
步骤4.1.1: sum = sum + pow(x,i)
步骤4.1.2: i = i+1
步骤4.2: 打印x、n和sum
步骤5 - 否则
步骤5.1: 打印无效的n值
步骤5.2: 跳转到重复步骤(跳转到步骤2)
步骤6 - 结束if
步骤7 - 停止
流程图
以下是计算几何级数算法的流程图:

程序
以下是计算**几何级数**的C程序:
#include <stdio.h>
#include <conio.h>
#include <math.h>
main(){
int x,n,sum=0,i;
start:
printf("enter the values for x and n:");
scanf("%d%d",&x,&n);
if(n>0){
for(i=0;i<=n;i++){
sum = sum+pow(x,i);
}
printf("The sum of the geometric progression is:%d",sum);
}
else{
printf("not a valid n:%d value",n);
getch();
goto start;
}
}输出
执行上述程序后,会产生以下结果:
enter the values for x and n:4 5 The sum of the geometric progression is:1365
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP