Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C คำนวณอนุกรมเรขาคณิต (Geometric Progression)

โจทย์

เขียนโปรแกรมอ่านค่า x และ n แล้วคำนวณผลรวมของอนุกรมเรขาคณิต:

1 + x + x^2 + x^3 + x^4 + ... + x^n

และพิมพ์ x, n และผลรวม

วิธีแก้

อัลกอริทึม

ขั้นตอน 1 - เริ่ม

ขั้นตอน 2 - วนซ้ำ

ขั้นตอน 3 - อ่านค่า x และ n ตอนรันไทม์

ขั้นตอน 4 - ถ้า n > 0 แล้ว

    ขั้นตอน 4.1: for i = 0 ถึง n ทำ sum = sum + pow(x,i)

    ขั้นตอน 4.2: พิมพ์ x, n และ sum

ขั้นตอน 5 - ไม่เช่นนั้น

    ขั้นตอน 5.1: พิมพ์ "not a valid n value"

    ขั้นตอน 5.2: goto repeat (ขั้นตอน 2)

ขั้นตอน 6 - จบ if

ขั้นตอน 7 - หยุด

Flowchart

มีแผนภาพ flowchart สำหรับอัลกอริทึมคำนวณอนุกรมเรขาคณิต

โปรแกรม

โปรแกรม 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