【问题标题】:C# out parameter problem in the get root methodC#get root方法中out参数问题
【发布时间】:2020-03-01 02:34:05
【问题描述】:

下面的代码从控制台获取 3 个输入,然后解析数字,然后将其发送到 getRealRoots 方法。找出它是否有 2、1 或没有根。 getrealroots中的out参数显示如下错误:

out 参数 'r1' 必须在控制离开之前分配给 当前方法

必须在控制离开当前方法之前分配 out 参数 'r2'

using System;

namespace Quadratic
{
    public class Program
    {
        static public void Main(string[] args)
        {

            Console.WriteLine("Enter three numbers, (A,B,C)");
            Double? a = GetDouble();
            Double? b = GetDouble();
            Double? c = GetDouble();

            getRealRoots(a, b, c,out r1,out r2);
            //throw new NotImplementedException("implement main");
        }





        static public int getRealRoots(double A, double B, double C, out double? r1, out double? r2)
        {
            double discriminant = B * B - 4 * A * C;

            if (discriminant > 0)
            {
                 r1 = (-B + Math.Sqrt(discriminant)) / (2 * A);
                 r2 = (-B - Math.Sqrt(discriminant)) / (2 * A);
                Console.WriteLine("The equation " + GetQuadraticString(A, B, C) + " has two real roots:" + r1 + " " + r2);
            }
            else if (discriminant == 0)
            {
                r1 = -B / (2 * A);
                Console.WriteLine("The equation " + GetQuadraticString(A, B, C) + " has one real root:" + r1);
            }
            else
            {
                Console.WriteLine("The equation " + GetQuadraticString(A, B, C) + " has no real roots:");
            }

        }

        //throw new NotImplementedException("write a method that uses out variables to return the real discriminants of a quadratic");

    }
}

【问题讨论】:

    标签: c# .net out


    【解决方案1】:

    首先,您有返回类型 int,但不返回 int。

    其次,错误消息表明,无论您的方法采用何种执行路径,您都必须为 out 参数分配一些值。您可以通过在方法开始时为其分配一些“默认”值来解决此问题。也许是这样的?:

    r1 = default (double);
    r2 = null;
    

    希望我能帮上忙

    【讨论】:

      【解决方案2】:

      作为 out 参数修饰符上的per the documentation

      作为输出参数传递的变量不必在传递到方法调用之前进行初始化。 但是,被调用的方法需要在方法返回之前赋值。

      对于您提供的代码,在方法@​​987654322@ 中,您是:

      • 设置r1r2 的输出值,其中discriminant > 0
      • 设置r1的输出值discriminant == 0,而不是r2的值
      • 不设置r1r2 不满足上述条件。

      由于被调用的方法需要赋值,您必须在每个执行路径中设置r1r2的值。

      由于您已将值定义为可为空的类型,因此您可以使用一些默认值开始您的方法来解决您的问题:

      static public int getRealRoots(double A, double B, double C, out double? r1, out double? r2)
      {
          r1 = null;
          r2 = null;
      
          // ... your method code
      }
      

      然后在您设置的特定 IF 条件下覆盖默认值。

      【讨论】:

        猜你喜欢
        • 2015-11-16
        • 2010-10-01
        • 1970-01-01
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多