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

โปรแกรม C แปลงตัวเลขเป็นคำอ่าน (Number to Words)

ได้รับสตริงตัวเลข ภารกิจคือแปลงเป็นคำอ่านภาษาอังกฤษ

เช่น "361" → "Three hundred sixty one"

ข้อจำกัด: รองรับได้สูงสุด 4 หลัก (0-9999)

ตัวอย่าง

Input: "1234"  Output: one thousand two hundred thirty four
Input: "7777"  Output: seven thousand seven hundred seventy seven

แนวทาง

  • รับค่าเป็นสตริง
  • เตรียมอาร์เรย์คำสำหรับ: หลักหน่วย, เลข 10-19, หลักสิบ (twenty, thirty...), หน่วยร้อย/พัน
  • ตรวจสอบความยาวสตริง แล้วประมวลผลตามตำแหน่งหลัก

อัลกอริทึม

Start
Step 1: ฟังก์ชัน convert(char *num)
    len = strlen(num)
    ถ้า len == 0 หรือ len > 4 แสดง error return
    เตรียมอาร์เรย์: single_digit[], tens_place[], tens_multiple[], tens_power[]
    ถ้า len == 1 พิมพ์ single_digit แล้ว return
    วนลูปจนกว่า *num == '\0':
        ถ้า len >= 3 (หลักร้อย/พัน):
            ถ้าตัวเลข != 0 พิมพ์ single_digit + tens_power[len-3]
            len--
        ถ้า len < 3 (หลักสิบ/หน่วย):
            ถ้าตัวแรก == '1' (10-19): รวมค่าสองหลักหา index ใน tens_place พิมพ์ return
            ถ้าตัวแรก == '2' และตัวที่สอง == '0': พิมพ์ "twenty" return
            มิฉะนั้น: พิมพ์ tens_multiple[ตัวแรก] แล้วพิมพ์ single_digit[ตัวที่สอง] ถ้าไม่ใช่ 0
    num++
Step 2: main() เรียก convert("9132")
Stop

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void convert(char *num) {
    int len = strlen(num);
    if (len == 0) { fprintf(stderr, "empty string\n"); return; }
    if (len > 4) { fprintf(stderr, "Length more than 4 is not supported\n"); return; }

    char *single_digit[] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
    char *tens_place[] = {"","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
    char *tens_multiple[] = {"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
    char *tens_power[] = {"hundred","thousand"};

    printf("\n%s: ", num);
    if (len == 1) { printf("%s\n", single_digit[*num - '0']); return; }

    while (*num != '\0') {
        if (len >= 3) {
            if (*num - '0' != 0) {
                printf("%s ", single_digit[*num - '0']);
                printf("%s ", tens_power[len-3]);
            }
            --len;
        } else {
            if (*num == '1') {
                int sum = *num - '0' + *(num+1) - '0';
                printf("%s\n", tens_place[sum]); return;
            } else if (*num == '2' && *(num+1) == '0') {
                printf("twenty\n"); return;
            } else {
                int i = *num - '0';
                printf("%s ", i ? tens_multiple[i] : "");
                ++num;
                if (*num != '0') printf("%s ", single_digit[*num - '0']);
            }
        }
        ++num;
    }
}

int main() {
    convert("9132");
    return 0;
}

ผลลัพธ์

nine thousand one hundred thirty two