-3

The variable the error is referring to is aNumber on line (32,17), how can I fix this?

using System;
class Calculation
{
    public static void Main(string[] data)
    {
        double result = Convert.ToDouble( data[0]);
        char op;
        double number;
        GetData(out op, out number);
        while (op != 'q' && op != 'Q')
        {
            switch (op)
            {
                case '+':
                    result += number;
                    break;
                case '-':
                    result -= number;
                    break;
                case '*':
                    result *= number;
                    break;
                case '/':
                    result /= number;
                    break;
            }
            Console.WriteLine("Result = " + result.ToString());
            GetData(out op, out number);
        }       
    }

    static void GetData(out char anOperator, out double aNumber)
    {
        string line;
        Console.Write("Enter an opertor and a number or 'q' to quit: ");
        line = Console.ReadLine();
        anOperator = Convert.ToChar(line.Substring(0, 1));
        if (anOperator != 'q' && anOperator != 'Q')
            aNumber = Convert.ToDouble(line.Substring(2));
    }
}
Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
user3555573
  • 21
  • 2
  • 7
  • 2
    `aNumber` isn't guaranteed assignment. Because it is an `out` parameter you need to assign it a value. – Ian R. O'Brien Sep 17 '15 at 15:38
  • @IanR.O'Brien Do you know why it isn't assigned the default value for its type if the programmer doesn't explicitly assign a value? Seems like that'd be the logical behavior, to me. – sab669 Sep 17 '15 at 15:56
  • @sab669 - That's a very good and different question that is too long to properly explain in comments. You should post it or see if there's already an answer. – Ian R. O'Brien Sep 17 '15 at 16:08
  • @IanR.O'Brien I suspect it'd be closed due to being too Open Ended :P – sab669 Sep 17 '15 at 16:08

1 Answers1

1

Add this to GetData method:

aNumber = 0;

Like this:

static void GetData(out char anOperator, out double aNumber)
{
      string line;
      Console.Write("Enter an opertor and a number or 'q' to quit: ");
      line = Console.ReadLine();
      anOperator = Convert.ToChar(line.Substring(0, 1));
      if (anOperator != 'q' && anOperator != 'Q')
           aNumber =  Convert.ToDouble(line.Substring(2));
      else
           aNumber = 0;
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109