开发者

How do I pass an array to a method that uses output parameters

I have a method that has 2 output parameters. The method should take an array and return both the sum and the average of the values in the array. There is another method that creates an array from user input. The array needs to be initialized from the main method. I am really stumped with this one. I hope you guys can help. I have included my code below.

// Create a console-based application whose Main() method declare开发者_高级运维s an array of eight integers.
//
// Call a method to interactivelyfill the array with any number of values up to eight.
//
// Call a second method that accepts out parameters for the arithmetic average and the sum of the values in the array.
//
// Display the array values, the number of entered elements, and their average and sum in the Main() method.


using System;

namespace ArrayManagment
{
    class Program
    {
        static void arrayMath(out int sum, out int avg)
        {
           sum = myArray.Sum();
           avg = myArray.Average();
        }
        static void displayArray(int[] myArray)
        {
            Console.Write("Your numbers are: ");
            for (int i = 0; i < 8; i++)
                Console.Write(myArray[i] + " ");
            Console.WriteLine();

        }

        static int[] fillArray()
        {
            int[] myArray;
            myArray = new int[8];
            int count = 0;
            do
            {
                Console.Write("Please enter a number to add to the array or \"x\" to stop: ");
                string consoleInput = Console.ReadLine();
                if (consoleInput == "x")
                {
                    return myArray;
                }
                else
                {
                    myArray[count] = Convert.ToInt32(consoleInput);
                    ++count;
                }

            } while (count < 8);

            return myArray;

        }

        static void Main(string[] args)
        {
            int[] myArray;
            myArray = new int[8];
            myArray = fillArray();
            int sum, avg;
            arrayMath(out sum, out avg);

            displayArray(myArray);


        }
    }
}


Just put it as a parameter before the output parameters:

static void arrayMath(int[] myArray, out int sum, out int avg)

(There is no need for it to be before the output parameters, but it just makes sense.)

Then send in the array to the method in the Main method:

arrayMath(myArray, out sum, out avg);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜