Как найти расчеты двумерных строковых массивов в двойном формате C #? - PullRequest
0 голосов
/ 16 февраля 2019

У меня есть консольное приложение в C #, которое позволяет пользователю вводить 5 дней недели, а затем 5 числовых значений, соответствующих дням в одном двумерном массиве.

Массив в строковом формате, поэтому япытался разобрать вторую половину строковых данных и получить их сумму, но там написано, что мой индекс вышел за пределы, есть идеи?

Код, размещенный ниже:

//Ask the user to enter five days of the week and rainfall data for each day

double rainsum = 0;

Console.WriteLine("Please enter 5 days of the week.");

//Store the data in a two dimensional string array named rainfallData[]
for (int i = 0; i < 2; i++)
{
  for (int j = 0; j < 5; j++)
  {
    rainfallData[i, j] = Console.ReadLine();
  }
  if (i == 0)
  {
    Console.WriteLine("Please enter the corresponding rain data.");
  }
}

Console.WriteLine("Data placed in raindallData[] array.");

for (int i = 0; i < 2; i++)
{
  Console.WriteLine();
  for (int j = 0; j < 5; j++)
  {
    Console.WriteLine("rainfallData({0},{1})={2}", i, j, rainfallData[i, j]);
  }
}

//Use iteration to calculate the following from the values in rainfallData[]:
//a) sum
Console.Write("Data values calculated using iteration. \n a) Sum of rainfallData[] = ");
for (int i = 1; i < rainfallData.Length; i++)
{
  Console.WriteLine();
  for (int j = 0; j < 5; j++)
  {
    rainsum += double.Parse(rainfallData[i, j]);
  }
}
Console.WriteLine(rainsum);

//End Program
Console.ReadKey(true);

1 Ответ

0 голосов
/ 16 февраля 2019

Ваша проблема в том, что rainfallData.Length относится к количеству элементов в массиве 2d - в вашем случае это 2 x 5 = 10, но вы помещали этот индекс в первое измерение и вызывали ошибку выхода за границы.

На вашем месте я бы начал свой код следующим образом:

int columns = 2;
int days = 5;

string [,] rainfallData = new string[columns, days];

Теперь каждый раз, когда речь идет о границах каждого измерения, используйте columns и days соответственно.

Вы бы написали свой код следующим образом:

//Ask the user to enter five days of the week and rainfall data for each day
Console.WriteLine("Please enter 5 days of the week.");

//Store the data in a two dimensional string array named rainfallData[]

for (int j = 0; j < days; j++)
{
    rainfallData[0, j] = Console.ReadLine();
}
Console.WriteLine("Please enter the corresponding rain data.");
for (int j = 0; j < days; j++)
{
    rainfallData[1, j] = Console.ReadLine();
}

Console.WriteLine("Data placed in raindallData[] array.");

for (int i = 0; i < columns; i++)
{
    Console.WriteLine();
    for (int j = 0; j < days; j++)
    {
        Console.WriteLine("rainfallData({0},{1})={2}", i, j, rainfallData[i, j]);
    }
}

//Use iteration to calculate the following from the values in rainfallData[]:
//a) sum
double rainsum = 0.0;
Console.Write("Data values calculated using iteration. \n a) Sum of rainfallData[] = ");
for (int i = 0; i < columns; i++)
{
    Console.WriteLine();
    for (int j = 0; j < days; j++)
    {
        rainsum += double.Parse(rainfallData[i, j]);
    }
}
Console.WriteLine(rainsum);

Просто для вашего наглядности вот как я мог бы действительно решить эту проблему:

int days = 5;

Console.WriteLine("Please enter 5 days of the week.");
string[] first = Enumerable.Range(0, days).Select(x => Console.ReadLine()).ToArray();

Console.WriteLine("Please enter the corresponding rain data.");
string[] second = Enumerable.Range(0, days).Select(x => Console.ReadLine()).ToArray();

string[][] rainfallData = new[] { first, second };

Console.WriteLine("Data placed in raindallData[][] jaggard array.");
Console.WriteLine(String.Join("", Enumerable.Range(0, days).Select(x => $"rainfallData[0][{1}]={rainfallData[0][x]}\n")));

Console.WriteLine(String.Join(Environment.NewLine, Enumerable.Range(0, days).Select(x => $"rainfallData[1][{1}]={rainfallData[1][x]}")));

double rainsum = rainfallData.Sum(i => i.Sum(j => double.Parse(j)));
Console.WriteLine($"Data values calculated using iteration. \n a) Sum of rainfallData[][] = {rainsum}");

Вот еще более надежный способ:

double[] readNumbers(int items, string title)
{
    Console.WriteLine($"Please enter {items} of {title} data.");
    int attempt = 0;
    return
        Enumerable
            .Range(0, items)
            .Select(x =>
            {
                double result;
                while (!double.TryParse(Console.ReadLine(), out result))
                {
                    Console.WriteLine($"Input not a number. Please try again.");
                }
                return result;
            })
            .ToArray();
}

int days = 5;

double[] first = readNumbers(days, "first columnn");
double[] second = readNumbers(days, "rain data");

double[][] rainfallData = new[] { first, second };

Console.WriteLine("Data placed in raindallData[][] jaggard array.");
Console.WriteLine(String.Join("", Enumerable.Range(0, days).Select(x => $"rainfallData[0][{1}]={rainfallData[0][x]}\n")));

Console.WriteLine(String.Join(Environment.NewLine, Enumerable.Range(0, days).Select(x => $"rainfallData[1][{1}]={rainfallData[1][x]}")));

double rainsum = rainfallData.Sum(i => i.Sum());
Console.WriteLine($"Data values calculated using iteration. \n a) Sum of rainfallData[][] = {rainsum}");
...