【问题标题】:How to ouput elements in array in reverse order using while loop in C#?如何使用C#中的while循环以相反的顺序输出数组中的元素?
【发布时间】:2016-07-06 10:15:17
【问题描述】:

我的问题是如何以相反的顺序输出数组中的东西 由两件事分组,仅诉诸while循环 (即没有for循环和Reverse方法等)

我知道第二个while循环不正确,但我不知道如何修改它。

提前感谢您的建议。

Console.WriteLine("Please type four things.");

const int MAX_SIZE = 4;
string[] things = new string[MAX_SIZE];
int i = 0;

while (i < MAX_SIZE)
{
    Console.WriteLine("Please type the things.");

    things[i] = Console.ReadLine();
    i++;
}

i = 0;

while (i < MAX_SIZE)
{
    Console.Write(things[i] + ", ");
    i--;
} 

【问题讨论】:

  • 澄清:你有一个数组 [1, 2, 3, 4, 5, 6]。您想以下一种方式输出它: (6, 5), (4, 3), (2, 1) 使用单个 while 循环。对吗?
  • 这是正确的,我应该成对输出,用逗号分隔。

标签: c# arrays while-loop


【解决方案1】:

试试

i = MAX_SIZE - 1
while (i >= 0)
{
    Console.Write(things[i] + ", ");
    i--;
}         

我使用MAX_SIZE-1 的原因是因为C# 中的数组是从0 开始的。第一个元素将始终位于位置 0。如果数组有 4 个元素,则最终元素将位于位置 3。

如果你想把东西分成两部分打印,你可以这样做:

i = MAX_SIZE - 1
while (i >= 0)
{
    Console.Write(things[i-1] + ", " things[i]);
    i -= 2;
}

【讨论】:

    【解决方案2】:

    您是否有任何理由要使用 while 循环而不是 for 循环?

    for(var i=0;i<MAX_SIZE;i++) {
        Console.WriteLine("Please type the things.");
    
                things[i] = Console.ReadLine();
                i++;
    }
    
    for(var i=MAX_SIZE-1;i>=0;i--){
        Console.Write(things[i] + ", ");
    }
    

    【讨论】:

    • 可能是因为它是家庭作业并且有一个人为的约束
    • 我对自己施加了这种人为的约束,以便更好地理解带有数组的 while 循环。到处都有限制,无论是在学术领域还是在工作中。上面带有 for 循环的示例看起来也很有趣且有用,我刚刚想到了另一个具体目标。
    • 您的示例帮助我更好地理解了代码的逻辑。谢谢你的建议。
    【解决方案3】:

    如果我正确理解了任务,下一个代码应该适合你:

    int i = things.Length - 1;
    while(i > 0)
    {
      Console.Write("({0}, {1}) ", things[i], things[i - 1]);
      i -= 2;
    }
    
    //in case the the list lenght is odd, output the last element without pair
    if(i == 0)
    {
      Console.Write("({0})", things[i]);
    }
    

    如果things 列表长度始终为偶数,则可以省略if 语句,因为仅当您需要发送没有对的最后一个(things 列表中的第一个)元素时才需要它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-16
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2019-06-25
      • 2019-09-14
      • 1970-01-01
      相关资源
      最近更新 更多