ntodorova

06_QuadraticEquation

Nov 1st, 2012
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.47 KB | None | 0 0
  1. using System;
  2.  
  3. class QuadraticEquation
  4. {
  5.     static void Main()
  6.     {
  7.         int a;
  8.         int b;
  9.         int c;
  10.         double x1;
  11.         double x2;
  12.  
  13.         Console.Write("Please enter the first number: ");
  14.         string firstStr = Console.ReadLine();
  15.  
  16.         Console.Write("Please enter the second number: ");
  17.         string secondStr = Console.ReadLine();
  18.  
  19.         Console.Write("Please enter the third number: ");
  20.         string thirdStr = Console.ReadLine();
  21.  
  22.         if (!int.TryParse(firstStr, out a))
  23.         {
  24.             Console.WriteLine("Invalid number: {0}", firstStr);
  25.         }
  26.         else if (!int.TryParse(secondStr, out b))
  27.         {
  28.             Console.WriteLine("Invalid number: {0}", secondStr);
  29.         }
  30.         else if (!int.TryParse(thirdStr, out c))
  31.         {
  32.             Console.WriteLine("Invalid number: {0}", thirdStr);
  33.         }
  34.         else
  35.         {
  36.             while (a == 0)
  37.             {
  38.                 Console.WriteLine("A must be different from 0!");
  39.                 string str = Console.ReadLine();
  40.  
  41.                 if (!int.TryParse(str, out a))
  42.                 {
  43.                     Console.WriteLine("Invalid number: {0}", str);
  44.                 }
  45.             }
  46.  
  47.             // Calculate the discriminant
  48.             double d = b * b - 4 * a * c;
  49.  
  50.             if (d < 0)
  51.             {
  52.                 Console.WriteLine("The equation doesn't have any real roots.");
  53.             }
  54.             else if (d == 0)
  55.             {
  56.                 x1 = (-b) / 2 * a;
  57.                 Console.WriteLine("The equation have only one real root: {0}", x1);
  58.             }
  59.             else
  60.             {
  61.                 x1 = (-b) + Math.Sqrt(d) / 2 * a;
  62.                 x2 = (-b) - Math.Sqrt(d) / 2 * a;
  63.                 Console.WriteLine("The real roots are:");
  64.                 Console.WriteLine("X1 is {0} and X2 is {1}", x1, x2);
  65.             }
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment