error of "use of unassigned local variable"

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • plasmay
    New Member
    • Mar 2010
    • 2

    error of "use of unassigned local variable"

    Hi, I am new in learning c#, and have recently encountered a problem:


    Code:
            static float ComputeAvg(float[] a)
            {
                float sum;
                int i;
                for (i = 0; i <= a.Length; i++)
                {
                    sum = sum + a[i];
                }
    
                float avg = sum / (i-1);
    
                return avg;
            }
    It comes with a exception says "sum" is "use of unassigned local variable". Since I have already declared "sum" outside the "for" loop, why it says "sum" is unassigned? Thanks!
    Last edited by tlhintoq; Mar 24 '10, 05:31 AM. Reason: [CODE] ...Your code goes between code tags [/CODE]
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.

    Originally posted by Plasmay
    Since I have already declared "sum" outside the "for" loop, why it says "sum" is unassigned?
    First let me compliment you on your use of 'declared' versus 'assigned'. A lot of people get those mixed up. And your answer is in those two different terms.

    You have 'declared' that the variable "sum" exists and that it is a float. But you have not 'assigned' it any value. It is always a good practice to assign a starting value when you create a variable.

    Code:
    float sum = 0.0f;

    Comment

    • plasmay
      New Member
      • Mar 2010
      • 2

      #3
      Thank you very much. I have found the answer right after I posted my question... Since I know a little about VB, and it will assign an default value for var when I didnt do so, so I was supposed...you know... Anyway, thanks for your reply. have a good night.

      Comment

      Working...