Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Related to Question at:
- //http://groups.google.com/group/dotnetdevelopment/browse_thread/thread/671641a749256799/
- public struct EquationSolution
- {
- private double[] solns;
- public EquationSolution(double[] solutions)
- {
- solns = (double[])solutions.Clone();
- }
- public int NumberOfSolutions
- {
- get { return solns.Length; }
- }
- public double this[int n]
- {
- get { return solns[n]; }
- }
- }
- public struct Equation
- {
- private double a, b, c;
- public Equation(double a, double b, double c)
- {
- this.a = a; this.b = b; this.c = c;
- }
- public EquationSolution Solve()
- {
- double[] solutions;
- if (a == 0)
- solutions = new double[] { (-c / b) };
- // Get the determinant.
- double d = (b * b) - 4 * a * c;
- if (d < 0)
- solutions = new double[0]; // No real solution.
- else if (d == 0)
- solutions = new double[1] { (-b / (2 * a)) }; // ONE real
- solution.
- else // if (d > 0)
- solutions = new double[2] { ((-b + Math.Sqrt(d)) / (2 * a)), ((-
- b - Math.Sqrt(d)) / (2 * a)) }; // TWO real solutions.
- return new EquationSolution(solutions);
- }
- }
- static void Main(string[] args)
- {
- string strEndProgram;
- Console.WriteLine("This program solves equation of the form [ax²+bx
- +c=0]");
- bool endProgram = false;
- do
- {
- Console.Write("Please enter the value of a:");
- double a = double.Parse(Console.ReadLine());
- Console.Write("Please enter the value of b:");
- double b = double.Parse(Console.ReadLine());
- Console.Write("Please enter the value of c:");
- double c = double.Parse(Console.ReadLine());
- Equation eq = new Equation(a, b, c);
- EquationSolution solutions = eq.Solve();
- switch(solutions.NumberOfSolutions)
- {
- case 0:
- System.Console.WriteLine("No Solution");
- break;
- case 1:
- Console.Out.WriteLine("The Solution is: {0:F1}", solutions
- [0]);
- break;
- case 2:
- Console.Out.WriteLine("The Solutions are: {0:F1}, {1:F1}",
- solutions[0], solutions[1]);
- break;
- }
- Console.Out.Write("Solve another equation? (y/n)");
- strEndProgram = Console.ReadLine();
- if(strEndProgram.StartsWith("n"))
- endProgram = true;
- } while(!endProgram);
- }
Advertisement
Add Comment
Please, Sign In to add comment