JulianJulianov

09.MethodsLab-Greater of Two Values

Feb 15th, 2020
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. 9. Greater of Two Values
  2. Create a method GetMax() that returns the greater of two values (the values can be of type int, char or string)
  3. Examples
  4. Input      Output
  5. int
  6. 2
  7. 16         16
  8. char
  9. a
  10. z          z
  11. string
  12. aaa
  13. bbb        bbb
  14.  
  15. using System;
  16.  
  17. namespace _09GreaterOfTwoValues
  18. {
  19.     class Program
  20.     {
  21.         static void Main(string[] args)
  22.         {
  23.             var type = Console.ReadLine();
  24.             var firstText = Console.ReadLine();
  25.             var secondText = Console.ReadLine();
  26.             var result = GetMax(type, firstText, secondText);
  27.             Console.WriteLine(result);
  28.         }   //Може и така: Console.WriteLine(GetMax(type, firstText, secondText));, но при
  29.             //положение, че не ми e нужна променливата result някъде в кода! В този случай нямам нужда от result.
  30.         private static string GetMax(string type, string firstText, string secondText)
  31.         {
  32.             var result1 = 0;
  33.             var result2 = 0;
  34.             if (type == "int")
  35.             {
  36.                 result1 = int.Parse(firstText);
  37.                 result2 = int.Parse(secondText);
  38.             }
  39.             else if (type == "char")
  40.             {
  41.                 result1 = char.Parse(firstText);
  42.                 result2 = char.Parse(secondText);
  43.             }
  44.             else if (type == "string")
  45.             {
  46.                 int comparison = firstText.CompareTo(secondText);    //Сравнение на string като числова стойност(ASCII)!
  47.                 if (comparison > 0)                            //Ако firstText > secondText, comparison = 1, иначе е -1!
  48.                 {
  49.                     return firstText;
  50.                 }
  51.                 else
  52.                 {
  53.                     return secondText;
  54.                 }
  55.             }
  56.             if (result1 > result2)
  57.             {
  58.                 return firstText;
  59.             }
  60.             else
  61.             {
  62.                 return secondText;
  63.             }
  64.         }
  65.     }
  66. }
Add Comment
Please, Sign In to add comment