如何将数组传递给使用输出参数的方法

时间:2011-02-28 01:18:53

标签: c# .net

我有一个有2个输出参数的方法。该方法应采用数组并返回数组中值的总和和平均值。还有另一种方法可以从用户输入创建数组。需要从main方法初始化该数组。我真的很难受这个。我希望你们能帮忙。我在下面提供了我的代码。

// Create a console-based application whose Main() method declares 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);


        }
    }
}

1 个答案:

答案 0 :(得分:4)

只需将其作为参数放在输出参数之前:

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

(不需要它在输出参数之前,但它只是有意义。)

然后将数组发送到Main方法中的方法:

arrayMath(myArray, out sum, out avg);