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

พิมพ์ N จำนวนแรกของอนุกรม (0.25, 0.5, 0.75, ...) ในรูปเศษส่วน

รับค่า N ซึ่งเทียบเท่ากับจำนวนพจน์ที่ต้องการพิมพ์

Input: N=5
Output: 0 1/4 1/2 3/4 1

อัลกอริทึม

START
Step 1 -> declare start variables as int num, den, i, n
Step 2 -> input number in n
Step 3 -> Loop For from i to 0 and i End For Loop
STOP

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

#include <stdio.h>

int main(int argc, char const *argv[]) {
    int num, den;
    int i, n;
    printf("Enter series limit\n");
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        if (i % 2 == 0) {
            if (i % 4 == 0) {
                num = i / 4;
                den = 0;
            } else {
                num = i / 2;
                den = 2;
            }
        } else {
            num = i;
            den = 4;
        }
        if (den != 0) {
            printf("%d/%d\n", num, den);
        } else {
            printf("%d\n", num);
        }
    }
    return 0;
}

ผลลัพธ์

Enter series limit
5
0
1/4
1/2
3/4
1