读取整数输入并打印矩阵

问题描述 投票:0回答:5

我正在尝试编写一个程序,从控制台读取一个正整数N(N <20)并打印一个像这样的矩阵:

N = 3
1 2 3
2 3 4
3 4 5

N = 5
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

这是我的代码:

using System;
namespace _6._12.Matrix
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Please enter N ( N < 20): ");
            int N = int.Parse(Console.ReadLine());
            int row;
            int col;
            for (row = 1; row <= N; row++)
            {
                for (col = row; col <= row + N - 1; )
                {
                    Console.Write(col + " ");
                    col++;
                }
                Console.WriteLine(row);
            }
            Console.WriteLine();
        }
    }
}

问题是控制台打印了一个额外的列,其数字从1到N,我不知道如何摆脱它。我知道为什么会发生这种情况,但仍无法找到解决方案。

c# matrix
5个回答
4
投票

简单,改变Console.WriteLine(row);Console.WriteLine();

而你在它;

    static void Main()
    {
        int N;

        do
        {
            Console.Write("Please enter N (N >= 20 || N <= 0): ");
        }
        while (!int.TryParse(Console.ReadLine(), out N) || N >= 20 || N <= 0);

        for (int row = 1; row <= N; row++)
        {
            for (int col = row; col <= row + N - 1; )
            {

                Console.Write(col + " ");
                col++;
            }
            Console.WriteLine();
        } 

        Console.Read();
    }

Please enter N (N >= 20 || N <= 0): 5
1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 
4 5 6 7 8 
5 6 7 8 9 

1
投票

只需将此行Console.WriteLine(row);更改为此Console.WriteLine();这里的问题是;在每个内循环的末尾,你再次写入行值;这是不需要的。


0
投票

第一个问题是你认为Console.WriteLine(行)在做什么?当你学习编程时,关键是“看到”代码正在做什么以及它为什么这样做,而不是运行它,调整它,然后再次运行它以查看它是否按照你想要的方式运行至。一旦你在头脑中清楚而简明地看到代码正在做什么,你会注意到Console.WriteLine(行)不对,你只需要在那一点写一个换行符。


0
投票

这是使用if语句而不是使用do while的另一种方法,代码看起来有点简单:

 static void Main(string[] args)
 {
     Console.Write("Give a number from 1 to 20: ");
     int n = int.Parse(Console.ReadLine());
     int row,col;
     Console.WriteLine("");
     if (n > 0 && n < 21)
     {
         for (row = 1; row <= n; row++)
         {
             for (col = row; col <= row + n - 1;col++ )
             {
                 Console.Write(col + " ");
             }

             Console.WriteLine();
         }
     }
     else
     {
         Console.WriteLine("This number is greater than 20 or smaller than 1");
     }
 }

0
投票

//以上所有答案我累了都错了你应该试一试然后回复我...

        Console.Write("Enter N: (N < 20) ");
        int n = Int32.Parse(Console.ReadLine());

        for (int row = 1; row <= n;row++)
        {
            Console.Write(row+" ");
            for (int col = row+1; col <= row + n - 1; )
            {
                Console.Write(col + " ");
                col++;
            }
            Console.WriteLine();

        }
        Console.ReadLine();
© www.soinside.com 2019 - 2024. All rights reserved.