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

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


โจทย์

แปลงตัวเลข 2 หลัก (0-99) เป็นคำอ่านภาษาอังกฤษ โดยไม่ใช้ switch case

ตรรกะ

  • 0-9: ใช้ array firstno[]
  • 10-19: ใช้ array firstno[] (เลข teens)
  • 20-99: แยกหลักสิบ (secondno[]) และหลักหน่วย (thirdno[])

โปรแกรมตัวอย่าง

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

int main() {
    int no;
    char *firstno[] = {"zero","ten","eleven","twelve","thirteen","fourteen",
                       "fifteen","sixteen","seventeen","eighteen","nineteen"};
    char *secondno[] = {"twenty","thirty","forty","fifty","sixty",
                        "seventy","eighty","ninety"};
    char *thirdno[] = {"one","two","three","four","five","six","seven","eight","nine"};
    
    printf("Enter number (0-99): ");
    scanf("%d", &no);
    
    if(no < 0 || no > 99)
        printf("Not a two-digit number\n");
    else if(no == 0)
        printf("Number: %s\n", firstno[0]);
    else if(no >= 10 && no <= 19)
        printf("Number: %s\n", firstno[no - 10 + 1]);
    else if(no >= 20 && no <= 99) {
        if(no % 10 == 0)
            printf("Number: %s\n", secondno[no/10 - 2]);
        else
            printf("Number: %s %s\n", secondno[no/10 - 2], thirdno[no%10 - 1]);
    }
    return 0;
}

ผลลัพธ์

enter a number: 79
the enter no is: seventy nine
enter a number: 234
enter number is not a two digit number