While 循环转义范围

发布于 2024-12-08 22:59:27 字数 325 浏览 0 评论 0原文

我有一个 while 循环,当我点击数字 1 到 5 时,我希望逃脱。

对此最好的声明是什么?

我目前有这个。

while (  oneChoice!= 1 ||  oneChoice!= 2 || oneChoice!= 3 || oneChoice!= 4 || oneChoice!= 5  )
{
cout << "Please make a selection" << endl;
cout << "Choose once more: ";
cin >> oneChoice;
break;
}

I have a while loop i wish to escape when i hit the number 1 through 5.

What would be the best statement to put for that?

I currently have this.

while (  oneChoice!= 1 ||  oneChoice!= 2 || oneChoice!= 3 || oneChoice!= 4 || oneChoice!= 5  )
{
cout << "Please make a selection" << endl;
cout << "Choose once more: ";
cin >> oneChoice;
break;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

美煞众生 2024-12-15 22:59:27

我会这样做:

int n;
for (;;)
{
    cout << "Please make a selection (1-5): "
    cin >> n;
    if (n >= 1 && n <= 5) break;
    cout << "You must choose a number from 1 through 5.\n";
}

中断位于中间,以便仅当用户输入可接受范围之外的值时才打印错误消息。 for (;;) 是适合您不希望在顶部或底部测试退出条件的循环的 C 族习惯用法。

I'd do it like this:

int n;
for (;;)
{
    cout << "Please make a selection (1-5): "
    cin >> n;
    if (n >= 1 && n <= 5) break;
    cout << "You must choose a number from 1 through 5.\n";
}

The break goes in the middle so that the error message is printed only if the user enters a value outside the acceptable range. for (;;) is proper C-family idiom for a loop where you don't want to have an exit condition tested at the top or bottom.

心欲静而疯不止 2024-12-15 22:59:27

假设 oneChoiceint(例如,因此不能有 1 到 2 之间的值),只需将条件更改为:

while (!(1 <= oneChoice && oneChoice <= 5))

or,等价:

while (oneChoice < 1 || oneChoice > 5)

另外,if oneChoice 在进入循环之前没有真正的意义或重要性,使用 do { ... } while (oneChoice < 1 || oneChoice > > ) 可能是更好的做法。 5); 改为循环。

Assuming oneChoice is an int (and thus can't have a value between 1 and 2, for example), just change the conditional to:

while (!(1 <= oneChoice && oneChoice <= 5))

or, equivalently:

while (oneChoice < 1 || oneChoice > 5)

Additionally, if oneChoice has no real meaning or importance before entering the loop, it would probably be better practice to use a do { ... } while (oneChoice < 1 || oneChoice > 5); loop instead.

长安忆 2024-12-15 22:59:27
while (oneChoice < 1 or oneChoice > 5)
{
    //
}
while (oneChoice < 1 or oneChoice > 5)
{
    //
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文