1

написала функцию swap, если отдельно попробовать поменять местами 2 элемента, то функция работает. Мне нужно максимальный элемент каждой строки поставить по позициям (0,0), (1,1), (2,2) итд(то есть по диагонали). только в этом случае функция вообще не работает(

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Аман7зерт
{
    class Program
    {

        static void Main(string[] args)
        {
         const int n=4, m=4;
            int i, j;
            int[,] array = new int[n, m];
            int max = 0;
            int index1 = 0;
            int index2 = 0;
            Random random = new Random();
            Console.WriteLine("Массив: ");
            for (i = 0; i < n; i++)
            {
                Console.WriteLine();
                for (j = 0; j < m; j++)
                {
                    array[i, j] = random.Next(0, 20);
                    Console.Write(array[i, j]+" ");
                }
            }


            for (i = 0; i < m; i++)
            {
                 max = array[i, 0];
                for ( j = 0; j < n; j++)
                {
                    if (array[i, j] > max)
                        max = array[i, j];
                    

                }
                Console.WriteLine("max:{0}", max);
                swap(ref array[index1, index2], ref array[i, j]);
                index1++; index2++;
            }
           
        

            for ( i = 0; i < n; i++)
            {
                Console.WriteLine();
                for (j = 0; j < m; j++)
                {
                    
                    Console.Write(array[i, j] + " ");
                }
            }

        }
        public static void swap(ref int a, ref int b)
        {
            int c;
            
            c = a;
            a = b;
            b = c;
        }
    }
}

1

1 ответ 1

1

Надо запомнить позицию максимального элемента в отдельную переменную.

Кстати, index1 и index2 вам вообще не нужны, они ведь равны i в этом цикле.

        for (i = 0; i < m; i++)
        {
            max = array[i, 0];
            int j_max = 0;
            for ( j = 0; j < n; j++)
            {
                if (array[i, j] > max)
                {
                    max = array[i, j];
                    j_max = j;
                }
            }
            Console.WriteLine("max:{0}", max);
            swap(ref array[i, i], ref array[i, j_max]);
        }
1
  • спасибо вам огромное!!!!!
    – Leyla
    9 июл 2020 в 17:05

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.