【问题标题】:for-loop seems to only run once when it should run until certain value reachedfor-loop 似乎只在它应该运行直到达到某个值时才运行一次
【发布时间】:2015-11-17 21:39:45
【问题描述】:

我有一些显示正确信息的代码,但循环只重复一次,我需要重复直到达到最大值。

    double x, v, max = .092 * Volt;
    int t = 0, resistance = initialResistance, stop = 0;

    System.out.print("\t");
    for (int column = initialResistance -= 100; column < finalResistance;       column += 100) {
        System.out.print(resistance + " \t");
        if (resistance < finalResistance) {
            resistance += 100;

        }

    }
    System.out.println("");
    for (int i = 0; i <= t; i += 10) {
        System.out.print("t:");
for (int j = initialResistance -= 100; j < resistance; j += 100) {
            if (resistance < finalResistance) {
                resistance += 100;

            }

            while (stop != 1)
            {
              resistance = initialResistance;
              for (int r = initialResistance -= 100; r <= resistance; r += 100) {
                if (resistance >= finalResistance)
                    {
                    resistance = finalResistance;
                    }
                    x = -(t / (resistance * capacitorValue));
                    v = Volt * (1 - Math.pow(BASE, x));
                    if (v <= max)

                 System.out.print("\t"+ String.format("%.2f", v));
                else
                 System.out.print("");

                if (r >= resistance && v > max)
                {
                 stop = 1;
                }
                 resistance += 100;
                }
                t += 10;
                System.out.println("");

            }
        }
    }

500 600 700
吨:0.00 0.00 0.00 0.00 0.00 0.00 0.00
0.92 0.77 0.67 0.67 0.67

t:t:t:

当 500 和 700 是初始和最终阻力并且 0.25 是电容值时的当前显示

所以它显示正确但需要重复更多,我需要摆脱额外的 0.00 和 .67 并弄清楚为什么它没有在第二行显示“t:”

【问题讨论】:

  • "[...] 但循环只重复一次。[...]" 您有多个循环。你说的是哪个循环?另外,请正确格式化您的代码,特别是如果您有嵌套结构。
  • 我不确定哪个循环有问题,我怎样才能更好地格式化它?
  • 看看你的缩进。最里面的while 里面有些部分有点乱。
  • 对吗,你总是在for循环的开头递减initialResistance,因为你使用了运算符-=而不是简单的减法。
  • 我改变了它,但它没有做任何改变代码

标签: java loops for-loop nested nested-loops


【解决方案1】:

我认为这是因为 initialResitance - 100resistance 小 100,如果 j(或 r)每次为 100 / 100 = 1 时都会增加 100

【讨论】:

    【解决方案2】:
    • 尽量简化您的代码。
    • 像这里这样的结构(for 循环中的 for 循环中的 for 循环中的 for 循环中的 for 循环)非常容易出错。
    • 尽量减少变量更改,尤其是循环终止变量。 (您在 6 个不同的地方更改了“阻力”的值。)
    • 不要在循环定义中引入副作用。 (如果您想减少“initialResistance”,请明确执行。)

    【讨论】:

      【解决方案3】:

      j 循环的第一次迭代期间,内部while(stop != 1) 循环被stop = 1 中断。当第二个j 迭代开始时,此标志变量保持设置。 while 循环再也不会进入,因为 stop 仍然是 1。

      请注意,在 while 循环之后将停止重置为“0”没有帮助。程序将无限期运行,因为t 在内部循环中递增,因此for(int i 循环永远不会停止。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-07
        • 1970-01-01
        相关资源
        最近更新 更多