Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Write a program that reads the coefficients a, b and c of a quadratic equation ax2+bx+c=0 and solves it (prints its real roots).
- */
- using System;
- class QuadraticEquation
- {
- static void Main()
- {
- double coefficientA, coefficientB, coefficientC, discriminantD;
- string invalidInput = "Invalid input! Please enter value between " + double.MinValue + " and " + double.MaxValue + "!" + Environment.NewLine; ;
- Console.WriteLine("ax^2 + bx + c = 0, a != 0");
- Console.WriteLine("Enter value of coefficient a: a = ");
- while (!(double.TryParse(Console.ReadLine(), out coefficientA) && coefficientA >= double.MinValue && coefficientA <= double.MaxValue && coefficientA != 0))
- {
- Console.WriteLine(invalidInput + "Coefficient \"a\" must be different from 0!" + Environment.NewLine);
- Console.WriteLine("Enter value of coefficient a: a = ");
- }
- Console.WriteLine("Enter value of coefficient b: b = ");
- while (!(double.TryParse(Console.ReadLine(), out coefficientB) && coefficientB >= double.MinValue && coefficientB <= double.MaxValue))
- {
- Console.WriteLine(invalidInput);
- Console.WriteLine("Enter value of coefficient b: b = ");
- }
- Console.WriteLine("Enter value of coefficient c: c = ");
- while (!(double.TryParse(Console.ReadLine(), out coefficientC) && coefficientC >= double.MinValue && coefficientC <= double.MaxValue))
- {
- Console.WriteLine(invalidInput);
- Console.WriteLine("Enter value of coefficient c: c = ");
- }
- discriminantD = (Math.Pow(coefficientB, 2)) - (4 * coefficientA * coefficientC);
- if (discriminantD < 0)
- {
- Console.WriteLine("The quadratic equation {0}x^2 + {1}x + {2} = 0 has no real roots because discriminant D = {3}" + Environment.NewLine, coefficientA, coefficientB, coefficientC, discriminantD);
- }
- if (discriminantD > 0)
- {
- double DRoot2 = Math.Sqrt(discriminantD);
- double resultX1 = (((-1) * coefficientB) + DRoot2) / (2 * coefficientA);
- double resultX2 = (((-1) * coefficientB) - DRoot2) / (2 * coefficientA);
- Console.WriteLine("The quadratic equation {0}x^2 + {1}x + {2} = 0 has two real roots: x1 = {3} and x2 = {4} and discriminant D = {5} !" + Environment.NewLine, coefficientA, coefficientB, coefficientC, resultX1, resultX2, discriminantD);
- }
- if (discriminantD == 0)
- {
- double resultX1 = (((-1) * coefficientB)) / (2 * coefficientA);
- Console.WriteLine("The quadratic equation {0}x^2 + {1}x + {2} = 0 has one real root: x1 = {3} and discriminant D = {4} !" + Environment.NewLine, coefficientA, coefficientB, coefficientC, resultX1, discriminantD);
- }
- Main();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment