C++程式碼用於判斷姓名是男性還是女性


假設,我們在一個數組 'input' 中給定 n 個字串。這些字串是姓名,我們需要找出它們是男性姓名還是女性姓名。如果一個姓名以 'a'、'e'、'i' 或 'y' 結尾;可以認為它是女性姓名。我們為字串中的每個輸入列印 'male' 或 'female'。

因此,如果輸入類似於 n = 5,input = {"Lily", "Rajib", "Thomas", "Riley", "Chloe"},則輸出將是 Female, Male, Male, Female, Female。

步驟

為了解決這個問題,我們將遵循以下步驟:

for initialize i := 0, when i < n, update (increase i by 1), do:
   s := input[i]
   l := size of s
   if s[l - 1] is same as 'a' or s[l - 1] is same as 'e' or s[l - 1] is same as 'i' or s[l - 1] is same as 'y', then:
      print("Female")
   Otherwise,
      print("Male")

示例

讓我們看看下面的實現,以便更好地理解:

#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int n, string input[]) {
   for(int i = 0; i < n; i++) {
      string s = input[i];
      int l = s.size();
      if (s[l - 1] == 'a' || s[l - 1] == 'e' || s[l - 1] == 'i' || s[l - 1] == 'y')
         cout<< "Female" << endl;
      else
         cout << "Male" << endl;
   }
}
int main() {
   int n = 5;
   string input[] = {"Lily", "Rajib", "Thomas", "Riley", "Chloe"};
   solve(n, input);
   return 0;
}

輸入

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

輸出

Female
Male
Male
Female
Female

更新於: 2022-03-29

857 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.