【问题标题】:breaking while loop and doesn't print the result c#打破while循环并且不打印结果c#
【发布时间】:2021-11-30 12:34:30
【问题描述】:

我是 C# 的初学者,我正在接受关于 codeforces 和 SPOJ 的培训,以学习如何解决问题, 我的问题是当循环中断时不会打印所有输入它只是结束程序而不打印

谁能告诉我我写的这两个代码有什么错误>

输入: 1,2,88,42,99 输出: 1,2,88

class Program

 {

  static void Main(string[] args)
    {
        Console.WriteLine("please enter an integer number in two digits");

        int numbers;
        int[] array_num = new int[100];

        string nu = "";
        int i =1;
      
         while(i<100)
         {
             numbers = int.Parse(Console.ReadLine());
             nu += numbers;
             array_num[i] = numbers;
             

            if(array_num[i]<array_num[i-1])

            {
                Console.WriteLine("the numbers is " +nu+ "");
                break;
            }

            i++;
            
           
         }
       
       }

      }

我在for循环中做同样的问题

   static void Main(string[] args)
    {
        Console.WriteLine("please enter an integer number in two digits");

        int numbers;
        int[] array_num = new int[50];

        string nu = "";

        for (int i = 1; i <= array_num.Length; i++)
        {
            numbers = int.Parse(Console.ReadLine());
            nu += numbers;
            array_num[i] = numbers;
           
            if (array_num[i] < array_num[i - 1])
            {

                Console.WriteLine("the number is " + nu + "");
                           
                break;
            }
           
        }

    }

错在哪里?

【问题讨论】:

  • 你想做什么?你的预期结果是什么? break 退出循环,因此您不会再打印任何行。 continue 带你进入下一个迭代,这就是你想要做的吗?
  • 不清楚。您是否希望它打印整个数组 - 甚至是满足条件的数组之后的数字?
  • 我需要用 if 条件结束输入,所以如果条件为真,打印输入并停止

标签: c# loops for-loop while-loop break


【解决方案1】:

回答“...问题是当循环中断时不会打印所有输入它只是结束程序...”

那是因为在你中断循环之后没有更多的代码可以执行 - 所以控制台关闭了。您可以在Main 方法的末尾添加Console.ReadKey()Console.ReadLine() 以在循环中断后保持控制台打开。 Console.ReadKey() 会等到您按下任意键,Console.ReadLine() 会等到您输入某些内容并按 Enter(或直接按 Enter)。或者在这两种情况下,控制台都将保持打开状态,直到您手动关闭它。

static void Main(string[] args)
{
    // ...
    for (int i = 1; i <= array_num.Length; i++)
    {
        // ...
        if (array_num[i] < array_num[i - 1])
        {
            Console.WriteLine("the number is " + nu + "");
            break;
        }
    }
    
    Console.ReadKey(); // Here Console will wait until you press any key and will stay opened
}

【讨论】:

  • 非常感谢您的帮助,我还有一个问题可以打印输出并保持控制台打开而不是关闭(ReadKey)?
  • 正如我在 aswer 中所说的,你可以使用Console.ReadLine(),它有点类似于ReadKey()。这是保持控制台打开的最简单方法。其他方式更具体或更复杂,不适合常用。
  • @leena almasnour 将答案标记为有用,如果它解决或有助于解决您的问题。
  • 完成,抱歉,我是新来的,我只是一个观众。
猜你喜欢
  • 1970-01-01
  • 2018-03-23
  • 2020-03-28
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 2021-10-12
  • 2016-12-24
  • 1970-01-01
相关资源
最近更新 更多