【发布时间】:2021-05-22 03:59:08
【问题描述】:
我编写了一个 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;
}
【问题讨论】:
-
在循环之前给 n 赋任何负值
-
@Ch3steR 问题是输出不一样,因为我遵循了 google 和 youtube 的教程。
-
在第二个代码示例中,由于
n未初始化,它可能恰好包含负数,也可能不包含。行为,特别是while循环条件在首次执行时是否为true,未定义。
标签: c++ loops while-loop do-while control-structure