Advertisement
sylviapsh

QuadraticEquationRoots

Dec 28th, 2012
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System;
  2. class QuadraticEquationRoots
  3. {
  4.   static void Main()
  5.   {
  6.     //Write a program that enters the coefficients a, b and c of a quadratic equation
  7.     //a*x2 + b*x + c = 0
  8.     //and calculates and prints its real roots. Note that quadratic equations may have 0, 1 or 2 real roots.
  9.  
  10.     Console.Write("Please enter the coefficient number a:");
  11.     double a = double.Parse(Console.ReadLine()); // quadratic coeficient a.
  12.     Console.Write("Please enter the coefficient number b:");
  13.     double b = double.Parse(Console.ReadLine()); // linear coeficient b
  14.     Console.Write("Please enter the constant term c:");
  15.     double c = double.Parse(Console.ReadLine()); // free term
  16.     double delta = b * b - 4 * a * c;
  17.     double x1, x2;
  18.  
  19.     if (a == 0 && b == 0 && c == 0)
  20.     {
  21.       Console.WriteLine("The possible roots are infinite!");
  22.     }
  23.     else if (a == 0 && b == 0 && c != 0)
  24.     {
  25.       Console.WriteLine("There are no real roots!");
  26.     }
  27.     else if (a == 0 && b != 0)
  28.     {
  29.       Console.WriteLine("Your equation is linear and has root x = {0}", -(c / b));
  30.     }
  31.     else if (delta < 0)
  32.     {
  33.       Console.WriteLine("The quadratic equation has no real roots.");
  34.     }
  35.     else
  36.     {
  37.       x1 = ((-b + Math.Sqrt(delta))) / (2 * a);
  38.       x2 = ((-b - Math.Sqrt(delta))) / (2 * a);
  39.       Console.WriteLine("The equation has roots x1={0} and x2={1}", x1, x2);
  40.     }
  41.   }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement