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

โปรแกรม C หาพจน์ที่ n ของลำดับเรขาคณิต (Geometric Progression)

ได้รับ a (พจน์แรก), r (อัตราส่วนร่วม), n (ลำดับพจน์) ภารกิจคือหาพจน์ที่ n

ลำดับเรขาคณิต (Geometric Progression) คือลำดับที่แต่ละพจน์ได้จากการคูณพจน์ก่อนหน้าด้วยอัตราส่วนร่วม

สูตร: GPₙ = a * r^(n-1)

ตัวอย่าง

Input: A=1, R=2, N=5  Output: 16 (ลำดับ: 1, 2, 4, 8, 16)
Input: A=1, R=2, N=8  Output: 128

แนวทาง

  • รับค่า a, r, n
  • คำนวณ nth term = a * pow(r, n-1)
  • แสดงผล

อัลกอริทึม

Start
Step 1: ฟังก์ชัน Nth_of_GP(int a, int r, int n)
    return a * (int)pow(r, n - 1)
Step 2: main() กำหนด a=1, r=2, n=8 เรียก Nth_of_GP แสดงผล
Stop

โค้ดตัวอย่าง

#include <stdio.h>
#include <math.h>

int Nth_of_GP(int a, int r, int n) {
    return a * (int)(pow(r, n - 1));
}

int main() {
    int a = 1, r = 2, n = 8;
    printf("The %dth term of the series is: %d\n", n, Nth_of_GP(a, r, n));
    return 0;
}

ผลลัพธ์

The 8th term of the series is: 128