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

Xác định tên nam/nữ dựa trên ký tự cuối bằng C++

Mô tả bài toán

Cho n tên. Nếu tên kết thúc bằng 'a', 'e', 'i', 'y' thì coi là nữ, ngược lại nam. In "Female" hoặc "Male" cho từng tên.

Ví dụ

input = {"Lily","Rajib","Thomas","Riley","Chloe"} → Female, Male, Male, Female, Female.

Thuật toán

Duyệt từng tên, lấy ký tự cuối, kiểm tra trong tập {'a','e','i','y'} (không phân biệt hoa thường).

Code C++

#include <bits/stdc++.h>
using namespace std;

void solve(int n, vector input) {
    for (string s : input) {
        char c = tolower(s.back());
        if (c=='a' || c=='e' || c=='i' || c=='y')
            cout << "Female";
        else
            cout << "Male";
        if (&s != &input.back()) cout << ' ';
    }
}

int main() {
    vector input = {"Lily","Rajib","Thomas","Riley","Chloe"};
    solve(5, input);
    return 0;
}

Đầu vào / Đầu ra

Input: 5, {"Lily","Rajib","Thomas","Riley","Chloe"}

Output: Female Male Male Female Female