Как получить пользовательский ввод для выбора строки в двумерном массиве? - PullRequest
0 голосов
/ 06 ноября 2019

Я пытаюсь написать программу, которая будет принимать сумму выбранной строки двумерного массива и показывать сумму с помощью пользовательского ввода для выбора конкретной строки. Как мне это сделать? Я пытался сделать это, но я не могу понять, как это сделать, не показывая КАЖДУЮ строку.

Мой код:

int[,] array1 = new int[6, 6]
{
    {10, 20, 10, 20, 21, 99 },
    {2, 27, 5, 45, 20, 13 },
    {17, 20, 20, 33, 33, 20 },
    {21, 35, 15, 54, 20, 37 },
    {31, 101, 25, 55, 26, 66 },
    {45, 20, 44, 12, 55, 98 }
};

int Length = array1.GetLength(0);
int Height = array1.GetLength(1);
int CalculateRow = 0;

for ( int i = 0; i < Length; i++ )
{
  for ( int j = 0; j < Height; j++ )
  {
    CalculateRow = CalculateRow + array1[i, j];
  }
  Console.Write("Enter the number of the Row you would like to see the sum of: ");
  int h = Convert.ToInt32(Console.ReadLine());
  if ( h > 5 )
  {
    Console.Write(-1);
  }
  else
    Console.WriteLine("The sum of Row {0} is {1} ", h, CalculateRow);
}

Ответы [ 4 ]

2 голосов
/ 06 ноября 2019

Вы можете использовать этот исправленный

int[,] array1 = new int[6, 6]
{
  {10, 20, 10, 20, 21, 99 },
  {2, 27, 5, 45, 20, 13 },
  {17, 20, 20, 33, 33, 20 },
  {21, 35, 15, 54, 20, 37 },
  {31, 101, 25, 55, 26, 66 },
  {45, 20, 44, 12, 55, 98 }
};

int Length = array1.GetLength(0);
int Height = array1.GetLength(1);
int CalculateRow = 0;

Console.Write("Enter the number of the Row you would like to see the sum of: ");
int h = Convert.ToInt32(Console.ReadLine());

if ( h < 0 || h >= Length )
{
  Console.Write(-1);
}
else
{
  for ( int j = 0; j < Height; j++ )
  {
    CalculateRow = CalculateRow + array1[h, j];
  }
  Console.WriteLine("The sum of Row {0} is {1} ", h, CalculateRow);
}

. Мы просим пользователя ввести индекс строки перед выполнением цикла по элементам выбранной строки, чтобы получить сумму.

Вы можете выполнить рефакторинг переменных

Чтобы иметь более согласованное и релевантное наименование, чтобы оно было более чистым.

А также используйте TryParse вместо Convert: он возвращаетfalse, если входная строка не может быть преобразована вместо исключения.

Например,

int[,] matrix = new int[6, 6]
{
  {10, 20, 10, 20, 21, 99 },
  {2, 27, 5, 45, 20, 13 },
  {17, 20, 20, 33, 33, 20 },
  {21, 35, 15, 54, 20, 37 },
  {31, 101, 25, 55, 26, 66 },
  {45, 20, 44, 12, 55, 98 }
};

int rowsCount = matrix.GetLength(0);
int columnsCount = matrix.GetLength(1);
int rowSum = 0;

Console.Write("Enter the number of the Row you would like to see the sum of ");
Console.Write("(0 to " + (rowsCount - 1) + "): ");
if ( !int.TryParse(Console.ReadLine(), out var rowIndex)
  || rowIndex < 0 
  || rowIndex >= rowsCount )
{
  Console.Write("Wrong index.");
}
else
{
  for ( int columnIndex = 0; columnIndex < columnsCount; columnIndex++ )
  {
    rowSum = rowSum + matrix[rowIndex, columnIndex];
  }
  Console.WriteLine("The sum of Row {0} is {1} ", rowIndex, rowSum);
}

Для отображения суммы каждой строки

for ( int rowIndex = 0; rowIndex < rowsCount; rowIndex++ )
{
  rowSum = 0;  // reset the sum between rows
  for ( int columnIndex = 0; columnIndex < columnsCount; columnIndex++ )
  {
    rowSum = rowSum + matrix[rowIndex, columnIndex];
  }
  Console.WriteLine("The sum of Row {0} is {1} ", rowIndex, rowSum);
}

Результат

The sum of Row 0 is 180
The sum of Row 1 is 112
The sum of Row 2 is 143
The sum of Row 3 is 182
The sum of Row 4 is 304
The sum of Row 5 is 274
0 голосов
/ 07 ноября 2019

Если вы планируете использовать List<int[]>, вы можете использовать метод Sum Линка и избежать вложенных циклов. Вот версия кода, которая делает то, что вам нужно.

    List<int[]> array1 = new List<int[]> { 
        new [] {10, 20, 10, 20 },
        new [] {3, 27, 5, 45 },
        new [] {17, 20, 20, 33 },
        new [] {21, 35, 15, 54 }
    };

    int input = 0;
    while(input < array1.Count)
    {
        Console.Write("Enter the number of the Row you would like to see the sum of: ");
        input = int.Parse(Console.ReadLine());
        if (input > array1.Count)
            Console.Write(-1);          
        else
        {
            int total = array1.ElementAt(input - 1).Sum(i => i);
            Console.WriteLine("The sum of Row {0} is {1} ", input, total);
        }
    }

HTH

0 голосов
/ 07 ноября 2019

Составьте список целых чисел для хранения суммы каждой строки, затем верните строку, которую запрашивает пользователь. В качестве альтернативы, спросите пользователя, какую строку он хочет , прежде чем вычислить сумму, и добавьте только значение if(h == i)

int[,] array1 = new int[6, 6]
{
    {10, 20, 10, 20, 21, 99 },
    {2, 27, 5, 45, 20, 13 },
    {17, 20, 20, 33, 33, 20 },
    {21, 35, 15, 54, 20, 37 },
    {31, 101, 25, 55, 26, 66 },
    {45, 20, 44, 12, 55, 98 }
};

int Length = array1.GetLength(0);
int Height = array1.GetLength(1);
List<int> CalculateRow = new List<int>(){0,0,0,0,0};

for ( int i = 0; i < Length; i++ )
{
  for ( int j = 0; j < Height; j++ )
  {
    CalculateRow[i] = CalculateRow + array1[i, j];
  }
  Console.Write("Enter the number of the Row you would like to see the sum of: ");
  int h = Convert.ToInt32(Console.ReadLine());
  if ( h > 5 )
  {
    Console.Write(-1);
  }
  else
    Console.WriteLine("The sum of Row {0} is {1} ", h, CalculateRow[h]);
}
0 голосов
/ 06 ноября 2019

Вы можете написать это так:

Console.Write("Enter the number of the Row you would like to see the sum of: ");
string input = Console.ReadLine();
int h;
//validates the input more safely
if(int.TryParse(input, out h) && h >= 0 && h < 6)
{
    int sum = 0;
    //loop over only the row that you care about
    for(int i = 0; i < 6; i++)
        sum += array1[h, i];

    Console.WriteLine("The sum of Row {0} is {1} ", h, sum);
}
else
{
    Console.WriteLine(-1);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...