将for循环转换为do-while循环

时间:2014-11-28 20:47:37

标签: java while-loop

我在几天前看到了一种使用for循环计算1到15的奇数乘积的方法:

int product = 1;        

for(int count = 1; count <= 15; count++){
    if (count % 2 != 0)
        product = product * count;
}

是否可以将其转换为do-while循环?

2 个答案:

答案 0 :(得分:0)

是:

int product = 1;
int count = 1;
do {
    if (count % 2 != 0) {
        product *= count;
    }
    count++;
} while (count <= 15)

更一般地说,每个for循环都可以在while循环中转换。

答案 1 :(得分:0)

当然可以

int product = 1;
int count = 1; // first part of the for loop
do {
    if (count % 2 != 0)
        product = product * count; // assuming product as been defined
    count++; // third part of the for loop
} while (count <= 15); // second part of the for loop

事实上,你也可以把它写成while循环。

int product = 1;
int count = 1;
while(count <= 15)
{
    if (count % 2 != 0)
        product = product * count; // assuming product as been defined
    count++;
}