问题描述
我编写了一个 C++ 程序,让用户使用 do while
循环输入正数。尽管如此,当我尝试将 do while
循环转换为 while
循环时,预期输出与 do while 循环不同。代码如下:
#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;
}
终端要求用户重新输入数字,直到我编写的上述代码为正。但是,我尝试将 do while
循环转换为 while
循环,如下所示,根本没有输出。
我可以知道我写错了哪一部分吗?谢谢。
#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;
}
解决方法
在您的代码的 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;
}
然后您需要稍微重新排列以获得相同的输出以及使用循环外的 n
的第一个输入。
例如,这将提供相同的输出:
#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;
}
,
你必须在while(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;
}
或者你可以用负数初始化它:
#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;
}