計算幾何級數的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

更新於:2021年9月1日

1K+瀏覽量

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告