-1

I wrote a quick code for factorizing formulas, however the line that takes creates the square root of D doesn’t work. The line is line 10. Any help is appreciated.

using System;
 public class MainClass {

 //Source Numbers
 public int A = 1;
 public int B = 3;
 public int C = 9;
 //Calculation Numbers
 public float Di;
 public static double Sqrt(double Di);   //This is the faulted line.
 //Answers
 public float X;
 public float X1;
 public float X2;

 public static void Main() {
Console.Writeline("D=", Di);
//Calculation for the Square root of D
 // (DSq)Math.Sqrt(Di);
   Di = B^2-4*A*C;
//Calculation for the answers
   if(Di>0) {
      X1 = ((0-B)-DSq)/(A*2);
      X2 = ((0-B)+DSq)/(A*2);
      Console.Writeline("X=", X1, " or X=", X2);
   }
   else if(Di=0) {
      X = 0-B;
      Console.Writeline("X=", X);
   }
   else {
   Console.Writeline("The formula cannot be solved.");
    }
   }
  }
pseyfert
  • 3,263
  • 3
  • 21
  • 47
  • 2
    Well yes, you're trying to declare a method with no body. How do you expect that to work? Also note that you're trying to use instance variables from a static method (without going via an instance) - that won't work either. – Jon Skeet Nov 30 '17 at 09:32

2 Answers2

1

You are using a method definition with no body. In any case you dont need to invent the wheel, since Math has already a Math.Sqrt(), method. Try:

........
Di = B^2-4*A*C;
if (Di>0)
{
  var sqrDi =   Math.Sqrt(Di);
  .....
}
...
apomene
  • 14,282
  • 9
  • 46
  • 72
0

You have several errors in your code, like the spelling of WriteLine, and comparing in if statements (use ==). This returns a list of valid solutions (X-values):

public IList<double> factorizeABC(double a, double b, double c)
{
    var solutions = new List<double>();
    var Di = b * b - 4 * a * c;
    if (Di > 0)
    {
        var rtDi = Math.Sqrt(Di);
        var X1 = (-b - rtDi) / (a * 2);
        var X2 = (-b + rtDi) / (a * 2);
        solutions.Add(X1);
        solutions.Add(X2);      
    }
    else if (Di == 0)
    {
        var X = -b / (a * 2);       
        solutions.Add(X);
    }
    return solutions;
}

usage:

var results = factorizeABC(1, 2, -8);

if (results.Count() == 0)
    Console.WriteLine("The formula cannot be solved.");
if (results.Count() == 1)
    Console.WriteLine("X=" + results[0].ToString());
if (results.Count() == 2)
    Console.WriteLine("X=" + results[0].ToString() + " or X=" + results[1].ToString());
AndrewR
  • 162
  • 1
  • 8