Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C in số thành chữ dùng if-else


Đề bài

Không dùng switch-case, in số 2 chữ số thành chữ bằng C.

Giải pháp

Kiểm tra 3 điều kiện:

  • if (no < 0 || no > 99) - Không phải 2 chữ số
  • else if (no == 0) - In "zero"
  • else if (no >= 10 && no <= 19) - In số 10-19 (riêng)
  • else if (no >= 20 && no <= 90) - In hàng chục + hàng đơn vị

Chương trình hoàn chỉnh

#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("Nhập số (0-99): ");
    scanf("%d", &no);
    
    if (no < 0 || no > 99)
        printf("Không phải số 2 chữ số\n");
    else if (no == 0)
        printf("Số nhập: %s\n", firstno[no]);
    else if (no >= 10 && no <= 19)
        printf("Số nhập: %s\n", firstno[no - 10 + 1]);
    else if (no >= 20 && no <= 99) {
        if (no % 10 == 0)
            printf("Số nhập: %s\n", secondno[no/10 - 2]);
        else
            printf("Số nhập: %s %s\n", secondno[no/10 - 2], thirdno[no%10 - 1]);
    }
    return 0;
}

Kết quả chạy

Nhập số: 79
Số nhập: seventy nine

Nhập số: 234
Không phải số 2 chữ số