Вычислить количество нулевых элементов и сумму отрицательных элементов - C#
Формулировка задачи:
Написать программу для вычисления количества нулевых элементов и сумму отрицательных элементов матриц А (3,4) и С (4,5) используя подпрограмму процедуру.
Напишите хотя бы пример пожалуйста.
Решение задачи: «Вычислить количество нулевых элементов и сумму отрицательных элементов»
textual
Листинг программы
using System;
static class IntMatrixOps
{
public static int ZeroCount(this int[,] matr)
{
int c = 0;
foreach (int i in matr) if (i == 0) c++;
return c;
}
public static int PositiveSum(this int[,] matr)
{
int s = 0;
foreach (int i in matr) if (i > 0) s+=i;
return s;
}
public static void FillByRandom(this int[,] matr,Random r = null)
{
r = r ?? new Random();
for (int i = 0; i < matr.GetLength(0); i++)
for (int j = 0; j < matr.GetLength(1); j++)
matr[i, j] = r.Next(-9,10);
}
public static void Show(this int[,] matr)
{
for (int i = 0; i < matr.GetLength(0); i++)
{
for (int j = 0; j < matr.GetLength(1); j++) Console.Write("{0,3}", matr[i, j]);
Console.WriteLine();
}
}
}
class test
{
static void Main()
{
Random r = new Random();
int[,] A = new int[3, 4];
A.FillByRandom(r);
Console.WriteLine("A : ");
A.Show();
Console.WriteLine("нули : "+A.ZeroCount());
Console.WriteLine("сумма положительных : " + A.PositiveSum());
int[,] B = new int[4,5];
B.FillByRandom(r);
Console.WriteLine("\nB : ");
B.Show();
Console.WriteLine("нули : " + B.ZeroCount());
Console.WriteLine("сумма положительных : " + B.PositiveSum());
Console.ReadKey(true);
}
}