lmarkov

Square Root

Jan 29th, 2013
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1. /*
  2.  * Write a program that reads an integer number and calculates and prints its square root. If the number is invalid or negative, print "Invalid number". In all cases finally print "Good bye". Use try-catch-finally.
  3. */
  4.  
  5. using System;
  6.  
  7. class SquareRoot
  8. {
  9.     static void Main()
  10.     {
  11.         try
  12.         {
  13.             SquareRootFromNumber();
  14.         }
  15.         catch (FormatException)
  16.         {
  17.             Console.WriteLine("Invalid number!");
  18.         }
  19.         finally
  20.         {
  21.             Console.WriteLine("Good bye!");
  22.         }
  23.  
  24.         Console.WriteLine();
  25.         Main();
  26.     }
  27.  
  28.     private static bool NegativeException(int number)
  29.     {
  30.         if (number < 0)
  31.         {
  32.             return true;
  33.         }
  34.         else
  35.         {
  36.             return false;
  37.         }
  38.     }
  39.  
  40.     private static void SquareRootFromNumber()
  41.     {
  42.         int number;
  43.         double squareRoot;
  44.        
  45.         Console.Write("Enter integer number: ");
  46.         number = int.Parse(Console.ReadLine());
  47.  
  48.         if(NegativeException(number) == true)
  49.         {
  50.             throw new FormatException();  
  51.         }        
  52.  
  53.         squareRoot = Math.Sqrt(number);
  54.  
  55.         Console.WriteLine("Square root from {0} = {1}", number, squareRoot);
  56.  
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment