C# Pasar matrices a funciones
En C#, puede pasar matrices como parámetros de una función. Puede pasar a la función un puntero a la matriz especificando el nombre de la matriz sin índices.
Ejemplo
El siguiente ejemplo demuestra cómo pasar matrices a funciones:
Ejemplo
using System;
namespace ArrayApplication
{
class MyArray
{
double getAverage(int[] arr, int size)
{
int i;
double avg;
int sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = (double)sum / size;
return avg;
}
static void Main(string[] args)
{
MyArray app = new MyArray();
/* una matriz int con 5 elementos */
int [] balance = new int[]{1000, 2, 3, 17, 50};
double avg;
/* pasar el puntero a la matriz como parámetro */
avg = app.getAverage(balance, 5 ) ;
/* mostrar el valor de retorno */
Console.WriteLine( "El promedio es: {0}", avg );
Console.ReadKey();
}
}
}
namespace ArrayApplication
{
class MyArray
{
double getAverage(int[] arr, int size)
{
int i;
double avg;
int sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = (double)sum / size;
return avg;
}
static void Main(string[] args)
{
MyArray app = new MyArray();
/* una matriz int con 5 elementos */
int [] balance = new int[]{1000, 2, 3, 17, 50};
double avg;
/* pasar el puntero a la matriz como parámetro */
avg = app.getAverage(balance, 5 ) ;
/* mostrar el valor de retorno */
Console.WriteLine( "El promedio es: {0}", avg );
Console.ReadKey();
}
}
}
Cuando el código anterior se compila y ejecuta, produce los siguientes resultados:
平均值是: 214.4Otras extensiones
C# Matrices