[英]How to convert do while loop to while loop in C++?
I have written a C++ program to let the users entering positive numbers using a do while
loop.我编写了一个 C++ 程序,让用户使用do while
循环输入正数。 Notwithstanding, when I try to convert the do while
loop into a while
loop, the expected output is not the same as do while loop.尽管如此,当我尝试将do while
循环转换为while
循环时,预期的 output 与 do while 循环不同。 The code is as below:代码如下:
#include <iostream>
using namespace std;
int main()
{
int n;
do
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0)
{
cout << "The integer you entered is negative. " << endl;
}
}
while (n < 0);
return 0;
}
The terminal requires the user to reenter the number until it is positive for the above code that I have written.终端要求用户重新输入数字,直到我编写的上述代码为正。 However, I try to convert the do while
loop to while
loop as shown below, there is no output at all.但是,我尝试将do while
循环转换为while
循环,如下所示,根本没有 output。
May I know which part I have written wrongly?我可以知道我写错了哪一部分吗? Thank you.谢谢你。
#include <iostream>
using namespace std;
int main()
{
int n;
while (n < 0)
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0){
cout << "The integer you entered is negative. " << endl;
}
}
return 0;
}
In the while
version of your code, you do not know what is n
a it is not initialized before you use it in the while (n<0)
.在您的代码的while
版本中,您不知道n
是什么,在您使用它之前它没有被初始化while (n<0)
。
int main()
{
int n;
// HERE YOU DO NOT KNOW IF n is NEGATIVE OR POSITIVE, YOU EITHER NEED TO INITIALIZE IT OR
// ENTER IT by cin >> n
while (n < 0)
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0){
cout << "The integer you entered is negative. " << endl;
}
}
return 0;
}
You then need to rearrange a little bit to get the same ouput as well as to use the first input of n
which is out of the loop.然后,您需要重新排列一点以获得相同的输出,并使用循环外的n
的第一个输入。
For instance, this will provide the same output:例如,这将提供相同的 output:
#include <iostream>
using namespace std;
int main()
{
int n=-1;
cout << "Enter a non-negative integer: ";
cin >> n;
while (n < 0)
{
if (n < 0)
{
cout << "The integer you entered is negative. " << endl;
cout << "Enter a non-negative integer: ";
cin >> n;
}
else
{
// if positive you get out of the loop
break;
}
}
return 0;
}
You have to take the n before while(n<0) statement:您必须在 while(n<0) 语句之前使用 n:
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter a non-negative integer: ";
cin >> n;
while (n < 0)
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0)
cout << "The integer you entered is "
<< "negative. " << endl;
}
return 0;
}
Or you may initialize it with negative number:或者你可以用负数初始化它:
#include <iostream>
using namespace std;
int main()
{
int n=-1;
while (n < 0)
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0)
cout << "The integer you entered is "
<< "negative. " << endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.