在 C# 中已经 return 了多个解之后,如何在二次方程函数中 return 额外的 x1 和 x2 值?

How can I return additional x1 and x2 values in quadratic equation function after already returning number of solutions in C#?

早上好,

我很难解决这个问题。任务内容如下:

"Create a static method double SolvingSquare (double a, double b, double c,? x1,? x2) returning the number of solutions, and in x1 and x2 possible solutions."


我已经找到了 return 个解决方案,但是我不知道如何在已经 return 个解决方案之后 return x1 和 x2。我试图写“?x1,?x2”参数,但随后出现红色下划线。我对这个很困惑。

static void Main(string[] args)
{

Console.WriteLine($"Number of Solutions: {Method.SolveSquare(1, 3, 1)}");

}
class Method
    {
        public Method()
        {}

        public static double SolveSquare(double a, double b, double c)
        {
            double delta = (b * b) - (4 * a * c);              
            double squareDelta = Math.Sqrt(delta);
            double x1 = (-b + squareDelta) / (2 * a);
            double x2 = (-b - squareDelta) / (2 * a);

            if(delta < 0)
            {
                return 0;

            } return (delta == 0) ? 1 : 2;
}

为了不剧透,还是帮到你:

你可能想要这样的东西......

double solutions = Solve(1,3,1, out double x1, out double x2);
Console.WriteLine($"We have {solutions} solutions, which are x1={x1} and x2={x2}");

// And the Solve Function:
public static double Solve(double a, double b, double c, out double x1, out double x2)
{
    // Implementation up to you, but somewhere must be:
    x1 = // Solution for x1;
    x2 = // Solution for x2;
}

另一个不相关的提示:如果 delta<0,实际上您不需要进行剩余的计算。您可以将 x1x2 设置为 double.NaN 和 return 0.

https://dotnetfiddle.net/VJch0u