Нужно вывести в поле label1 номер столбца матрицы с наименьшей суммой. Как это сделать?

Вот, что у меня пока есть:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace дз
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.RowCount = 4; 
            dataGridView1.ColumnCount = 5;
            int[,] a = new int[4, 5];
            int i, j;
            
            Random rand = new Random();
            for (i = 0; i < 4; i++)
                for (j = 0; j < 5; j++)
                    a[i, j] = rand.Next(1, 100);
            //выводим матрицу в dataGridView1
            for (i = 0; i < 4; i++)
                for (j = 0; j < 5; j++)
                    dataGridView1.Rows[i].Cells[j].Value = a[i, j].ToString();
            



        }

        private void button2_Click(object sender, EventArgs e)
        {

            int sum = 0;
            for (int k = 0; k < dataGridView1.Rows.Count; ++k)
            {
                sum += Convert.ToInt32(dataGridView1.Rows[k].Cells[1].Value);

                label1.Text = sum.ToString();
            }
        }
    }
}
  • Вопрос задан
  • 50 просмотров
Пригласить эксперта
Ответы на вопрос 1
Создаем отедельный массив `sum`, в котором будем хранить/считать сумму каждого столбца:

int[] sum = new int[5];
int max = Int32.MinValue;
int maxColumnIndex = 0;
for (int k = 0; k < dataGridView1.Rows.Count; ++k)
{
    for(int j = 0; j < dataGridView1.Rows[k].Cells.Count; j++)
    {
        var colSum = sum[j] + Convert.ToInt32(dataGridView1.Rows[k].Cells[j].Value);
        sum[j] = colSum;
        if(colSum > max){
            max = colSum;
            maxColumnIndex = j;
        }
    }
}

label1.Text = maxColumnIndex.ToString();
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы