繁体   English   中英

for循环似乎只在应该运行直到达到特定值时才运行一次

[英]for-loop seems to only run once when it should run until certain value reached

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

    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("");

            }
        }
    }

500600700
t:0.00 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是初始和最终阻力,而.25是capacticorValue

因此它可以正确显示,但需要重复更多,我需要删除多余的0.00和.67并弄清楚为什么第二行不显示“ t:”

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

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

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

  • 尝试简化您的代码。
  • 像您这样的结构(while循环中的for循环,for循环中的for循环)非常容易出错。
  • 最小化变量更改,尤其是对于循环终止变量。 (您可以在6个不同的位置更改“电阻”的值。)
  • 不要在循环定义中引入副作用。 (如果要减少“ initialResistance”,请明确进行。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM