【问题标题】:While loop looking for unexpected input for no reason?While 循环无缘无故地寻找意外的输入?
【发布时间】:2013-10-26 21:44:30
【问题描述】:

我正在尝试运行与输入无关的 while 循环程序。它只是应该告诉我计算的最终值是多少。但是,当我运行该程序时,它什么也不做。它也没有结束。我对正在发生的事情感到困惑?

int x = 90;
    while (x < 100)
    {
        x += 5;
        if (x > 95)
            x -= 25;
    }
    System.out.println( "final value for x is " + x);

【问题讨论】:

  • 它总是在循环中,所以它永远不会到达 println :) 如果你想知道它是否有效,请将 println 放入循环中。
  • 你期望的结果是什么?

标签: loops input while-loop


【解决方案1】:

循环永远不会终止,因为 x 永远不会达到 100。如果您想亲自查看 x 发生了什么,请在循环中添加一行,使代码如下所示:

int x = 90;
while (x < 100) {
    System.out.println("x = " + x);  // More useful output here...
    x += 5;
    if (x > 95)
        x -= 25;
}
System.out.println("final value for x is " + x);

【讨论】:

    【解决方案2】:

    发生的情况是您的 while 循环永远不会停止,因此它永远不会打印某些内容,请尝试更改循环内的代码。

    你怎么能意识到这一点?

    while 循环中输出一些打印内容:

        int x = 90;
        System.out.println("Before the while");
        while (x < 100) {
            System.out.println("Inside the while");
            x += 5;
            if (x > 95)
                x -= 25;
        }
        System.out.println("final value for x is " + x);
    

    迭代 1:

    x = 95
    

    迭代 2:

    x = 100
    if condition is true, so x = 75
    

    ...因此,每当 x 达到 100 时,条件将使其变为 75。因此,while 永远不会结束。

    【讨论】:

    • 我认为这是我教授的意图。他只是想让我们弄清楚结果是什么。我只是想确保我的执行没有做错任何事情。
    猜你喜欢
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多