Search code examples
c#.netout

C# out parameter problem in the get root method


This code below grabs 3 inputs from the console and then parses the numbers, after it then gets sent to getRealRoots method. which finds whether it has 2, 1 or no roots. The out parameters in the getrealroots are showing the following error:

The out parameter 'r1' must be assigned to before control leaves the current method

The out parameter 'r2' must be assigned to before control leaves the current method

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

    }
}

error message that pops up


Solution

  • First, you have the return type int, but do not return an int.

    Second, the error message says that you have to assign your out parameters some value no matter what path of execution your method takes. You could solve this by assigning them some "default" values at the beginning of the method. Maybe like this?:

    r1 = default (double);
    r2 = null;
    

    Hope I could help