二维数组中的列和行?

Posted

技术标签:

【中文标题】二维数组中的列和行?【英文标题】:Columns and rows in a 2D array? 【发布时间】:2021-03-03 07:28:15 【问题描述】:
        
        int woodchuckSim = 0;
        int numOfDays = 0;
        bool validNumber = false;
        bool validDays = false;
        Random ran1 = new Random();
        
        //display banner

        //Ask user how many woodchucks to simulate
        while(!validNumber)
        
            Write("How many woodchucks would you like to simulate? (1 - 100) ");
            int.TryParse(ReadLine(), out woodchuckSim);
            if((woodchuckSim <= 0) || (woodchuckSim > 100))
            
                WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
            
            else
            
                validNumber = true;
            
        

        //Ask user how many days to simulate
        while(!validDays)
        
            Write("\nHow many days would you like to simulate? (1 - 10) ");
            int.TryParse(ReadLine(), out numOfDays);
            if((numOfDays <= 0) || (numOfDays > 10))
            
                WriteLine("Please enter a positive whole number between 1 and 10: ");
            
            else
            
                validDays = true;
            
        

        //Using random class populate each cell between 1 and 50 that represents # of pieces of wood chucked by specific woodchuck on that specific day
        int[,] sim = new int[woodchuckSim, numOfDays];

        WriteLine($"woodchuckSim numOfDays");
        for (int i = 0; i < sim.GetLength(0); i++)
        
            for (int j = 0; j < sim.GetLength(1); j++)
            
                sim[i, j] = ran1.Next(1, 50);
                Write(sim[i, j] + "\t");
            
            
                WriteLine(i.ToString());
            
        
        WriteLine("Press any key to continue...");
        ReadLine();
    

到目前为止,这是我在土拨鼠模拟编码作业中的代码,但我需要像图片一样在侧面和顶部添加列和行标签。我真的不知道如何做到这一点,我不确定我是否遗漏了代码或输入了错误。同样在代码的末尾,它会打印出直线模拟的土拨鼠数量,就像用户输入 15 一样,它会在最后以直线打印 0-14,这不是我想要的,任何帮助都是赞赏,谢谢! (第二张图是我的代码打印的)

【问题讨论】:

【参考方案1】:

有几个步骤可以做到这一点,但并不难:

    写入列标题(在行标题所在的开头包含空格 列下划线 对于每一行,先写行标题 然后对行中的每一列,写入列数据 列数据写入后,写一个换行符开始下一行

这是一个生成与您的输出类似的表格的示例。请注意,我们使用PadLeft 用空格填充每列数据,因此它们的宽度都相同。根据您在下面的评论,我还包括了 SumAvg 列。此外,为了清理主要代码,我添加了以不同颜色编写文本的方法以及从用户那里获取整数的方法:

private static readonly Random Random = new Random();

private static void WriteColor(string text,
    ConsoleColor foreColor = ConsoleColor.Gray,
    ConsoleColor backColor = ConsoleColor.Black)

    Console.ForegroundColor = foreColor;
    Console.BackgroundColor = backColor;
    Console.Write(text);
    Console.ResetColor();


private static void WriteLineColor(string text,
    ConsoleColor foreColor = ConsoleColor.Gray,
    ConsoleColor backColor = ConsoleColor.Black)

    WriteColor(text + Environment.NewLine, foreColor, backColor);


public static int GetIntFromUser(string prompt, Func<int, bool> validator = null)

    var isValid = true;
    int result;

    do
    
        if (!isValid)
        
            WriteLineColor("Invalid input, please try again.", ConsoleColor.Red);
        
        else isValid = false;

        Console.Write(prompt);
     while (!int.TryParse(Console.ReadLine(), out result) ||
                (validator != null && !validator.Invoke(result)));

    return result;


public static void Main()

    int columnWidth = 6;

    ConsoleColor sumForeColor = ConsoleColor.DarkRed;
    ConsoleColor sumBackColor = ConsoleColor.Gray;
    ConsoleColor avgForeColor = ConsoleColor.White;
    ConsoleColor avgBackColor = ConsoleColor.DarkGreen;

    int numWoodchucks = GetIntFromUser(
        "How many woodchucks would you like to simulate? (1 - 100) ... ",
        x => x >= 1 && x <= 100);
    int numDays = GetIntFromUser(
        "How many days would you like to simulate? (1 - 10) .......... ",
        x => x >= 1 && x <= 10);
    int[,] data = new int[numWoodchucks, numDays];

    // Write column headers, starting with a blank row header
    Console.WriteLine();
    Console.Write(new string(' ', columnWidth));
    for (int col = 1; col <= data.GetLength(1); col++)
    
        Console.Write($"col".PadLeft(columnWidth));
    
    Console.Write(" ");
    WriteColor("Sum".PadLeft(columnWidth - 1), sumForeColor, sumBackColor);
    Console.Write(" ");
    WriteLineColor("Avg".PadLeft(columnWidth - 1), avgForeColor, avgBackColor);

    // Write column header underlines
    Console.Write(new string(' ', columnWidth));
    for (int col = 0; col < data.GetLength(1); col++)
    
        Console.Write(" _____");
    
    Console.Write(" ");
    WriteColor("_____", sumForeColor, sumBackColor);
    Console.Write(" ");
    WriteLineColor("_____", avgForeColor, avgBackColor);

    int total = 0;

    for (int row = 0; row < data.GetLength(0); row++)
    
        // Write row header
        Console.Write($"row + 1 |".PadLeft(columnWidth));

        int rowSum = 0;

        // Store and write row data
        for (int col = 0; col < data.GetLength(1); col++)
        
            data[row, col] = Random.Next(1, 50);
            Console.Write($"data[row, col]".PadLeft(columnWidth));
            rowSum += data[row, col];
        

        // Write sum and average
        Console.Write(" ");
        WriteColor($"rowSum".PadLeft(columnWidth - 1),
            sumForeColor, sumBackColor);
        Console.Write(" ");
        WriteLineColor($"Math.Round((double) rowSum / data.GetLength(1), 1):F1"
            .PadLeft(columnWidth - 1), avgForeColor, avgBackColor);

        total += rowSum;
    

    // Write the sum of all the items
    Console.Write(new string(' ', columnWidth + columnWidth * data.GetLength(1) + 1));
    WriteColor("_____", sumForeColor, sumBackColor);
    Console.Write(" ");
    WriteLineColor("_____", avgForeColor, avgBackColor);

    // Write the average of all the items
    Console.Write(new string(' ', columnWidth + columnWidth * data.GetLength(1) + 1));
    WriteColor($"total".PadLeft(columnWidth - 1), sumForeColor, sumBackColor);
    Console.Write(" ");
    WriteLineColor(
        $"Math.Round((double) total / (data.GetLength(0) * data.GetLength(1)), 1):F1"
        .PadLeft(columnWidth - 1), avgForeColor, avgBackColor);

    Console.Write("\nPress any key to continue...");
    Console.ReadKey();

输出

【讨论】:

你太棒了,非常感谢!您是否知道如何将所有随机数相加并得到土拨鼠数量的平均值? 我用SumAvg 列更新了示例以进行演示【参考方案2】:

未测试,但类似这样:

    Write("\t");
    for (int i = 0; i < sim.GetLength(0); i++)
    
        Write(i.ToString() + "\t");
    
    WriteLine("\t");
    for (int i = 0; i < sim.GetLength(0); i++)
    
        Write("_____\t");
    
    WriteLine();

   for (int i = 0; i < sim.GetLength(0); i++)
    
        
            WriteLine(i.ToString().PadLeft(3) + " |\t");
                    
        for (int j = 0; j < sim.GetLength(1); j++)
        
            sim[i, j] = ran1.Next(1, 50);
            Write(sim[i, j] + "\t");
        
    

就像我说的,未经测试,只是在此处直接输入编辑器,但这应该会让您接近。另外,请查看 string.PadLeft(int) 函数以使您的数字像示例一样右对齐。

【讨论】:

以上是关于二维数组中的列和行?的主要内容,如果未能解决你的问题,请参考以下文章

打印一个numpy数组的所有列和行[重复]

如何将 Pandas DataFrame 的列和行子集转换为 numpy 数组?

如何一次比较二维数组的2列与python中另一个数组的列

jquery怎么获取二维数组的最后一个和除了最后一个以外的数据并输出?

如何获取二维数组的列数

使用 Ionic 3 将生成的 Blob 下载到 Android 设备中