【问题标题】:How do I print # in a nested for loop [duplicate]如何在嵌套的 for 循环中打印 # [重复]
【发布时间】:2018-07-02 13:27:33
【问题描述】:
 for (int i = 0; i <= 6; i++)
 {
     string[] doors = new string[6];
     doors[i] = "#";
     for (int j = 1; j <=i; j++)
         {
            Console.Write(doors[j]); 
         }
     Console.Writeline():
} 

大家好。我需要打印 # 一个然后 # 两次,直到我达到六次。它说 System.index.out.of.range。怎么会?

【问题讨论】:

  • 你根本不需要任何 array - string[] doors -。只需打印出# - Console.Write('#')
  • 那么我该如何声明#呢?
  • 见上例
  • @Kobus:你不想声明任何东西。只需在循环中打印出 constant #Console.Write('#');

标签: c#


【解决方案1】:

您应该尝试扩展您的数组,它被限制为 6 个元素,但您尝试在从 0 到 6 时访问 7 个元素。

for (int i = 0; i <= 6; i++)
 {
     string[] doors = new string[7];
     doors[i] = "#";
     for (int j = 1; j <=i; j++)
         {
            Console.Write(doors[j]); 
         }
     Console.Writeline():
} 

【讨论】:

    【解决方案2】:

    如果

    我需要打印 # 一次,然后 # 两次,直到我达到六次。

    你不需要任何 数组 - string[] doors = new string[6];,只是循环:

    for (int line = 1; line <= 6; ++line) {
      for (int column = 1; column <= line; ++column) {
        Console.Write('#'); 
      }
    
      Console.WriteLine(); 
    }
    

    如果您必须使用数组(即数组将在其他地方使用),请摆脱幻数:

    // Create and fill the array
    string[] doors = new string[6];
    
    for (int i = 0; i < doors.Length; i++) 
      doors[i] = "#";
    
    // Printing out the array in the desired view
    for (int i = 0; i < doors.Length; i++) {
      for (int j = 0; j < i; j++) {
        Console.Write(doors[j]); 
      } 
    
      Console.Writeline(); 
    }
    

    请注意数组是从零开始的(带有6 项的数组有0..5 索引)

    【讨论】:

      【解决方案3】:

      因为它超出了范围。

      改成这样:

      for (int i = 0; i <= 6; i++)
       {
           string[] doors = new string[6];
           doors[i] = "#";
           for (int j = 0; j <=i.length; j++)
               {
                  Console.Write(doors[j]); 
               }
           Console.Writeline():
      } 
      

      【讨论】:

      • 你想让i.length在这里做什么?鉴于 i 是int,它实际上正在做的事情的答案可能是引发编译器错误......
      【解决方案4】:

      无需使用 2 个循环。就repeat that character

      for (int i = 0; i <= 6; i++)
      {
        Console.Write(new String("#",i)); 
        Console.WriteLine():
      } 
      

      【讨论】:

        猜你喜欢
        • 2011-10-22
        • 2019-02-27
        • 1970-01-01
        • 2012-11-30
        • 1970-01-01
        • 2012-09-14
        • 2023-04-06
        • 2015-10-21
        • 2021-02-14
        相关资源
        最近更新 更多