gpt4 book ai didi

c++ - while 循环不适用于第二个循环

转载 作者:搜寻专家 更新时间:2023-10-31 01:30:16 26 4
gpt4 key购买 nike

我正在尝试输入一个整数并仅在该数字 <= 2000 时打印它,否则要求用户一次又一次地重新输入该数字。

当我输入一个大于 2000 的数字时,它要求我再次输入数字(这正是我想要做的),如果我输入一个大于 2000 的数字再次,它什么都不做.似乎循环一直在运行,但我不知道我做错了什么。感谢您的帮助。

这是用 C++ 编写的代码。

#include <iostream>

using std::cout;
using std::endl;
using std::cin;

int main(){

unsigned int a = 0 ;
int out = 1;

cout << "Please enter a number : " << endl;

while (out){
cin >> a;
if (a > 2000) {
cout << "Number is greater than 2000 !" << endl;
cout << endl;
cout << "Please enter the number again : " << endl;
cin >> a;
out = 1;
} else {
cout << "Your entered number is : " << endl << a << endl;
out = 0;
}
}
return 0;
}

最佳答案

and if I enter a number greater than 2000 again it does nothing

不对,等你进入下一个cin输入。因为你有两个 cin s 在 a 的循环中值大于 2000,第二个 cin没有得到提示。

你的程序可以简化很多,改while loop部分如下

while (out){
cin >> a;
out=a>2000?1:0;
if(out)
cout<<"Enter number again ";
}

关于c++ - while 循环不适用于第二个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48251698/

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