Here's how I refactored the code:

---
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);
}
---

Points to note:

1. Removed the "Solver" struct/class altogether. It makes more sense
as an instance method of the Equation class.
2. Converted both classes to structs, removed unnecessary constructor,
used a single one.
3. Cleaned up the code to make the flow clearer.

HTH,
--
Cerebrus.

On Jul 13, 4:07 pm, thread <[email protected]> wrote:
> i think this is the soft stomech of this code lines,my only way is to
> add some kind of indexer that if there is solution it will be fliped
> to 1 and when there is no solution it will alocate it to 0 anyway so
> it will not crash down
> but i'm not sure its the smartest way

Reply via email to