Advertisement
emzone

Homework 4.6. Quadtratic Equation

Mar 23rd, 2014
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.04 KB | None | 0 0
  1. /*Problem 6.    Quadratic Equation
  2. Write a program that reads the coefficients a, b and c of a quadratic equation ax^2 + bx + c = 0 and solves it
  3. (prints its real roots). */
  4.  
  5. using System;
  6.  
  7.     class QuadraticEquation
  8.     {
  9.         static void Main()
  10.         {
  11.             Console.Write("a: ");
  12.             string a = Console.ReadLine();
  13.             double aDouble;
  14.             if (!double.TryParse(a, out aDouble))
  15.             {
  16.                 Console.WriteLine("Wrong data for coefficient \"a\"!");
  17.             }
  18.             Console.Write("b: ");
  19.             string b = Console.ReadLine();
  20.             double bDouble;
  21.             if (!double.TryParse(b, out bDouble))
  22.             {
  23.                 Console.WriteLine("Wrong data for coefficient \"b\"!");
  24.             }
  25.             Console.Write("c: ");
  26.             string c = Console.ReadLine();
  27.             double cDouble;
  28.             if (!double.TryParse(c, out cDouble))
  29.             {
  30.                 Console.WriteLine("Wrong data for coefficient \"c\"!");
  31.             }
  32.             if (aDouble != 0)    // Coefficient "a" can't be 0
  33.             {
  34.                 double discriminant = (bDouble * bDouble) - (4*aDouble*cDouble);
  35.                 if (discriminant > 0)
  36.                 {
  37.                     double x1 = ((-1 * bDouble) + Math.Sqrt(discriminant) / (2 * aDouble));
  38.                     double x2 = ((-1 * bDouble) - Math.Sqrt(discriminant) / (2 * aDouble));
  39.                     Console.WriteLine("x1: " + x1);
  40.                     Console.WriteLine("x2: " + x2);
  41.                 }
  42.                 else if (discriminant == 0)
  43.                 {
  44.                     double x1 = (-1 * bDouble) / (2 * aDouble);
  45.                     double x2 = x1;
  46.                     Console.WriteLine("x1: " + x1);
  47.                     Console.WriteLine("x2: " + x2);
  48.                 }
  49.                 else if (discriminant < 0)
  50.                 {
  51.                     Console.WriteLine("There are no real roots. The discriminant is smaller than 0.");
  52.                 }
  53.             }
  54.         }
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement