我看到很多关于将 for 循环转换为 while 并执行 while 循环的问题,但我似乎找不到任何关于将 while 循环转换为 C++ 中的 while 循环的内容。它仍然需要保持与原始代码相同的功能。
这是原始代码:
int number, product = 1, count = 0;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
while (number != 0)
{
product = product * number;
count++;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
}
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}
通过移动它,我能够在这里结束,但我一直以错误结束。当我运行程序时,它会提示我输入一个数字,就像预期的那样。如果我输入一个有效数字,它会循环并问我同样的问题。然后当我输入0时,它像往常一样踢出,但无论之前输入的数字如何,它都显示产品为0。
这是我尝试将其调整为 do while 循环:
int main()
{
int number, product = 1, count = 0;
do
{
cout << "Enter a whole number to be included in the product" << endl << "or enter 0 to end the input: ";
cin >> number;
product = product * number;
count++;
}
while (number != 0);
{
if (count > 0)
cout << endl << "The product is " << product << "." << endl;
}
}