简体   繁体   English

努力将for循环转换为do..while循环

[英]Struggling to convert for loop into do..while loop

I'm struggling to convert a for loop into a do..while loop, seems like an unnecessary exercise to me but maybe it'll be useful to me later on. 我正在努力将for循环转换为do..while循环,这对我来说似乎是不必要的练习,但也许以后对我很有用。 I can't get my head round how I'd re-design it, I can pretty easily put it into a while loop but not a do..while. 我不知道如何重新设计它,我可以很容易地将它放入while循环中,而不是do..while。

The for loop is below; for循环在下面;

    int d;
    int n = 55;

    for (d = 0; n != 0; d++)
    {
        n /= 10;
    }
    System.out.println(d);

Any help is appreciated :) 任何帮助表示赞赏:)

I think this will do: 我认为这可以做到:

    int d = 1;
    while ((n /= 10) != 0) {
        d++;
    }

Here's a solution without do .. while / while but a simple infinite loop (which has the greatest flexibility): 这是一个没有do .. while / while而是一个简单的无限循环(具有最大灵活性)的解决方案:

int d = 0;
int n = 55;
// loop
while (true) {
    n /= 10;
    d++;
    //break condition
    if (n == 0) {
        break;
    }
}
System.out.println(d);
int d;
int n = 55;

d = 0;
do {
    n /= 10;
    d++;
} while(n != 0)

System.out.println(d);

this way the d variable, which just count how many times the loop is executed, will be updated the same way as the for loop would do. 这样,仅计算循环执行次数的d变量将以与for循环相同的方式进行更新。

Note that this will work only if n is not 0 at the beginning of the loop. 请注意,这仅在循环开始时n不为0时有效。 In other words, if n is set to 0 in the second line of code the result will be different from the for loop, because the do..while loop always gets executed at least once, therefore the output would be 0 in the "for loop" case and 1 in the "do..while loop" case. 换句话说,如果在第二行代码中将n设置为0,则结果将与for循环不同,因为do..while循环始终至少执行一次,因此在“ for”中输出将为0。循环”情况,“ do..while循环”情况下为1。

You could implement it with a do...while loop like 您可以使用do...while循环来实现它

int d = 0;
int n = 55;

do {
    n /= 10;
    d++;
} while (n != 0);
System.out.println(d);

But I would suggest you use Integer.toString(int) and take the length of the resulting String instead like, 但我建议您使用Integer.toString(int)并采用结果String的长度,例如

System.out.println(Integer.toString(n).length());

try this: 尝试这个:

 int d=0;
 int n = 55;
 do{ 
  n /= 10;
  d++;
 }while(n != 0);
 System.out.println(d);

all loops are the same, basically they need a condition . 所有循环都是相同的,基本上它们需要一个condition in your case your condition is (n!=0) . 在您的情况下,您的条件是(n!=0) for loop is good because its 'tidier'. for循环很好,因为它的“更整洁”。

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

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