Advertisement
Spocoman

03. Month Printer(switch , ternary operator and array solutions)

Nov 2nd, 2023 (edited)
600
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. Решение със switch:
  2.  
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8.     int number;
  9.     cin >> number;
  10.  
  11.     string result = "";
  12.  
  13.     switch (number) {
  14.     case 1:
  15.         result = "January";
  16.         break;
  17.     case 2:
  18.         result = "February";
  19.         break;
  20.     case 3:
  21.         result = "March";
  22.         break;
  23.     case 4:
  24.         result = "April";
  25.         break;
  26.     case 5:
  27.         result = "May";
  28.         break;
  29.     case 6:
  30.         result = "June";
  31.         break;
  32.     case 7:
  33.         result = "July";
  34.         break;
  35.     case 8:
  36.         result = "August";
  37.         break;
  38.     case 9:
  39.         result = "September";
  40.         break;
  41.     case 10:
  42.         result = "October";
  43.         break;
  44.     case 11:
  45.         result = "November";
  46.         break;
  47.     case 12:
  48.         result = "December";
  49.         break;
  50.     default:
  51.         result = "Error!";
  52.         break;
  53.     }
  54.    
  55.     cout << result << endl;
  56.     return 0;
  57. }
  58.  
  59. Решение с тернарен оператор:
  60.  
  61. #include <iostream>
  62.  
  63. using namespace std;
  64.  
  65. int main() {
  66.     int number;
  67.     cin >> number;
  68.  
  69.     string result =
  70.         number == 1 ? "January" :
  71.         number == 2 ? "February" :
  72.         number == 3 ? "March" :
  73.         number == 4 ? "April" :
  74.         number == 5 ? "May" :
  75.         number == 6 ? "June" :
  76.         number == 7 ? "July" :
  77.         number == 8 ? "August" :
  78.         number == 9 ? "September" :
  79.         number == 10 ? "October" :
  80.         number == 11 ? "November" :
  81.         number == 12 ? "December" : "Error!";
  82.      
  83.     cout << result << endl;
  84.     return 0;
  85. }
  86.  
  87. Решение с масив:
  88.  
  89. #include <iostream>
  90.  
  91. using namespace std;
  92.  
  93. int main() {
  94.     int number;
  95.     cin >> number;
  96.  
  97.     string months[13] = {
  98.         "Error!",
  99.         "January",
  100.         "February",
  101.         "March",
  102.         "April",
  103.         "May",
  104.         "June",
  105.         "July",
  106.         "August",
  107.         "September",
  108.         "October",
  109.         "November",
  110.         "December"
  111.     };
  112.  
  113.     cout << months[number > 0 && number < 13 ? number : 0] << endl;
  114.     return 0;
  115. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement