Как можно решить данную задачу через методы?
Как можно решить данную задачу через методы, чтобы в методе Main было только объявление массива и не более одной Int переменной? Если можно, то самым простым способом.
string s;
int z = 0;
int max, min;
Console.WriteLine("Введите элементы массива");
s = Console.ReadLine();
string[] str = s.Split(' ');
int[] a = new int[str.Length];
for (int i = 0; i < str.Length; i++)
{
a[i] = Convert.ToInt32(str[i]);
}
Console.WriteLine("Введите минимальный элемент ");
min = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите максимальный элемент ");
max = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Индексы элементов");
for (int i = 0; i < a.Length; i++)
{
if ((a[i] > min) && (a[i] < max))
{
Console.Write("{0} ", i);
z++;
}
}
Console.WriteLine($"{Environment.NewLine}Количество индексов: {z}");
Ответы (1 шт):
Автор решения: Aarnihauta
→ Ссылка
Обратите внимание, что для работы данного кода необходимо подключить пространство имен: using System.Linq;
Если вы не хотите использовать автоматический поиск Min и Max, а хотите получать их с клавиатуры, то замените соответствующие методы на int minOrMax = Convert.ToInt32(Console.ReadLine());
static void Main(string[] args)
{
Console.WriteLine("Введите элементы массива");
string str = Console.ReadLine();
int[] arr = GetIntArray(str);
//В метод как аргументы передаю массив и два метода, которые возвращают в своем теле int
int count = GetIndexCount(arr, GetMin(arr), GetMax(arr));
Console.WriteLine($"{Environment.NewLine}Количество индексов: {count}");
}
private static int[] GetIntArray(string str)
{
string[] strArray = str.Split(' ');
int[] intArray = new int[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
intArray[i] = Convert.ToInt32(strArray[i]);
return intArray;
}
private static int GetIndexCount(int[] array, int min, int max)
{
int count = 0;
for (int i = 0; i < array.Length; i++)
{
if ((array[i] > min) && (array[i] < max))
{
count++;
Console.Write("{0} ", i);
}
}
return count;
}
private static int GetMin(int[] array)
{
return array.Min();
}
private static int GetMax(int[] array)
{
return array.Max();
}