我写了一个用于分解公式的快速代码,但是创建D的平方根的行不起作用。该行是第10行。感谢任何帮助。
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.");
}
}
}
答案 0 :(得分:1)
您正在使用没有正文的方法定义。在任何情况下,您都不需要发明轮子,因为Math
已经有Math.Sqrt()
方法。尝试:
........
Di = B^2-4*A*C;
if (Di>0)
{
var sqrDi = Math.Sqrt(Di);
.....
}
...
答案 1 :(得分:0)
您的代码中有几个错误,例如WriteLine的拼写和if语句中的比较(使用==)。这将返回有效解决方案(X值)的列表:
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;
}
用法:
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());