Having trouble writing program to find average of numbers

Discussion in 'C#' started by check2010, Sep 9, 2010.

  1. check2010

    check2010 New Member

    Sep 9, 2010
    Likes Received:
    Trophy Points:
    Hello all.

    I have an assignment in which I'm required to find the average of a sequence of nonnegative numbers entered by the user, where the user enters a negative number to terminate the input. I've gotten the termination to work successfully, but I'm having trouble calculating the average.

    As you can see, my code takes the next number in the sequence and divides it by the number of terms that have been used at that point. Unfortunately that isn't what I want. If only there was some way I could set the first entered number equal to a certain variable, the second to another, and so on. Can anyone give me a suggestion? Below is my code.

    	static void Main(string[] args)
                double input = 0, average = 0; 
                int numberOfTerms = 1;
                Console.WriteLine("To end this program, enter a negative number and press any key.");
                while (input >= 0)
                    Console.Write("Enter a number in your sequence: ");
                    input = Double.Parse(Console.ReadLine());
                    if (input > 0)
                        average = input / numberOfTerms;
                    numberOfTerms = numberOfTerms + 1;
                    Console.WriteLine("The average so far is {0}.", average);

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice