我在几天前看到了一种使用for循环计算1到15的奇数乘积的方法:
int product = 1;
for(int count = 1; count <= 15; count++){
if (count % 2 != 0)
product = product * count;
}
是否可以将其转换为do-while循环?
答案 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++;
}