gpt4 book ai didi

c++ - 如何阻止它无限重复,但仍保持循环?

转载 作者:行者123 更新时间:2023-11-28 06:11:01 25 4
gpt4 key购买 nike

在第 33 行,有一个 break 来阻止代码无限重复,但我希望它参与 while 循环

代码:

#include <iostream>
using namespace std;
int main()
{
while (true){
{
cout << "This program counts by twos to any number that is inputted by the user." << endl;
cout << "Input an even number to start counting." << endl;
int input;
cin >> input;
if (!cin.fail())//fails if input is not an integer
{
if (input < 0)//makes sure all numbers are positive
{
cout << "That is not a positive number. Try again?" << endl;
}
else if (input % 2 != 0) // makes sure all numbers are even
{
cout << "That is not an even number. Try again?" << endl;
}
else{
for (int i = 0; i <= input; i += 2) //uses a for loop to actually do the counting once you know that the number is even.
{
cout << i << endl;

}
}

}
if (cin.fail())//returns this when you input anything other than an integer.
{
cout << "That is not a digit, try again." << endl;
break;
}
}
}
return 0;
}

如果你们能帮我找出为什么会重复,那真的很有帮助。

最佳答案

为了退出循环,需要在for循环后添加break语句。如果没有 break,for 循环将执行并打印您的输出,然后控制将落到 while 循环的末尾,它将从循环的顶部开始。

我还建议将 if (cin.fail()) 更改为 else,因为您已经在检查 if (!cin.fail()) 。如果您想再次循环,还需要忽略其余输入并清除错误标志。

您在 while 循环中还有一组额外的括号。通过这些更改,您的代码将是:

#include <iostream>
#include <limits>
using namespace std;
int main()
{
while (true)
{
cout << "This program counts by twos to any number that is inputted by the user." << endl;
cout << "Input an even number to start counting." << endl;
int input;
cin >> input;
if (!cin.fail())//fails if input is not an integer
{
if (input < 0)//makes sure all numbers are positive
{
cout << "That is not a positive number. Try again?" << endl;
}
else if (input % 2 != 0) // makes sure all numbers are even
{
cout << "That is not an even number. Try again?" << endl;
}
else{
for (int i = 0; i <= input; i += 2) //uses a for loop to actually do the counting once you know that the number is even.
{
cout << i << endl;

}
break; // exit the while loop
}

}
else //else when you input anything other than an integer.
{
cout << "That is not a digit, try again." << endl;
cin.clear(); // reset the error flags
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear any extra input
}
}
return 0;
}

关于c++ - 如何阻止它无限重复,但仍保持循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31272514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com