Kvadratická rovnice
Zdroják k výpočtu kvadratické rovnice v consolové aplikaci C# .NET
java
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
ExtendedMath extMath = new ExtendedMath();
double a, b, c;
a = double.Parse(Console.ReadLine());
b = double.Parse(Console.ReadLine());
c = double.Parse(Console.ReadLine());
Console.WriteLine("Roots are " + extMath.GetRoots(a, b, c));
Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);
}
}
class ExtendedMath
{
public QuadraticRoots GetRoots(double a, double b, double c)
{
if (a == 0)
throw new Exception("Zero exception");
double d = GetDiscriminant(a, b, c);
QuadraticRoots roots = new QuadraticRoots();
// (-b +- sqrt(d) ) / 2a
if (d >= 0)
{
roots.x1 = (-b + Math.Sqrt(d)) / 2 * a;
if (d != 0)
roots.x2 = (-b - Math.Sqrt(d)) / 2 * a;
}
return roots;
}
private double GetDiscriminant(double a, double b, double c)
{
// b^2 - 4ac
return Math.Pow(b, 2) - 4 * a * c;
}
}
struct QuadraticRoots
{
public double? x1, x2;
public override string ToString()
{
if (x1 == null && x2 == null)
return "Not defined in real numbers";
else if (x2 == null)
return string.Format("x1 = {0}", x1);
else
return string.Format("x1 = {0} x2 = {1}", x1, x2);
}
}
Neformátovaný
Přidáno: 23.8.2013
Expirace: Neuvedeno