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

Chương trình C++ chuyển chữ số thành từ dùng câu lệnh điều kiện

Cho chữ số d, chuyển thành từ. Ví dụ d=9 → "Nine". Nếu d ngoài [0,9] in thông báo phù hợp.

Ví dụ: d=3 → "Three"

Giải thuật

  • Hàm solve(d): chuỗi if-else if kiểm tra d từ 0 đến 9, in từ tương ứng
  • Nếu d<0 hoặc d>9: "Beyond range of 0 - 9"
  • Main: đọc d, gọi solve(d)

Ví dụ minh họa

#include <iostream> 
using namespace std; 

void solve(int d){ 
    if(d < 0 || d > 9){ 
        cout << "Beyond range of 0 - 9"; 
    }else if(d == 0){ cout << "Zero"; }
    else if(d == 1){ cout << "One"; }
    else if(d == 2){ cout << "Two"; }
    else if(d == 3){ cout << "Three"; }
    else if(d == 4){ cout << "Four"; }
    else if(d == 5){ cout << "Five"; }
    else if(d == 6){ cout << "Six"; }
    else if(d == 7){ cout << "Seven"; }
    else if(d == 8){ cout << "Eight"; }
    else if(d == 9){ cout << "Nine"; }
} 

int main(){ 
    int d; 
    cin >> d; 
    solve(d); 
} 

Đầu vào

3

Đầu ra

Three