2012-08-06 140 views
0

我试图写一个程序,从控制台读取一个正整数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,我不知道如何摆脱它。我有一个想法,为什么这可能会发生,但仍然无法找到解决方案。

+0

首先检查ñ<20或者是否会再次要求用户把一个数<20 – 2012-08-06 06:14:03

回答

4

简单,对于Console.WriteLine();

变化Console.WriteLine(row);,而你在它;

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 
+0

奥基。额外的列消失了,但现在是一个数字:N + 1出现在第一列不需要的地方。 – 2012-08-06 06:31:22

+1

@AngelElenkov,你能告诉我在哪里? – Fredou 2012-08-06 06:39:04

1

只是此行Console.WriteLine(row);改变这种Console.WriteLine(); 这里的问题是;在每个内部循环的末尾,您正在再次写入行值;这是不需要的。

0

第一个问题是你认为Console.WriteLine(row)在做什么?当你正在学习编程时,要“看”代码在做什么以及为什么要这样做,而不是运行它,调整它,然后再次运行,看看它是否按照你想要的方式行事至。一旦你清楚而明了地看到代码在做什么,你会注意到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"); 
    } 
}