我试图制作一个程序,要求用户输入3个数字。每个数字必须介于1和1000之间。我遇到了while循环的问题,因为我无法弄清楚循环无法无限运行的正确陈述。如果该数字小于1但大于1000,则会要求用户再次输入一个数字。
# include <iostream>
using namespace std;
int a, b,c, sum;
int main (){
cout << "Enter first number:";
cin >> a;
while ( a <=1 || a<=1000)
cout<< "Entered number must between 1 .. 1000";
cout << "Enter second number:";
cin >> b;
if ( b <=1 || b <=1000)
cout<< "Entered number must between 1 .. 1000";
cout << "Enter third number:";
cin >> c;
if ( c <=1 || c <=1000)
cout<< "Entered number must between 1 .. 1000";
sum = a+b+c;
cout << a <<"+"<<b << "+"<< c << "Your sum is: " << sum << endl;
return 0;
}
答案 0 :(得分:0)
这是一个密集的示例,应该向您展示一些技巧:
<强> Live On Coliru 强>
#include <iostream>
#include <limits>
namespace {
void ignore_rest_of_line(std::istream& is) {
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
void try_recover(std::istream& is) {
if (is.eof())
throw std::runtime_error("Unexpected end of input");
is.clear();
ignore_rest_of_line(is);
}
}
template <typename T, typename Validator>
T prompt(std::string label, Validator f) {
T value;
while (true) {
std::cout << "Enter " << label << ": ";
if (std::cin >> value) {
if (f(value))
return value;
} else {
std::cerr << "Invalid input\n";
try_recover(std::cin);
}
}
// unreachable
}
int main() {
auto validate = [](int i) { return i>=2 && i<=999; };
int a = prompt<int>("first number (2..999)", validate);
int b = prompt<int>("second number (2..999)", validate);
int c = prompt<int>("third number (2..999)", validate);
int sum = a + b + c;
std::cout << a << "+" << b << "+" << c << " Your sum is: " << sum << std::endl;
}
打印
Enter first number (2..1000): a
Invalid input
Enter first number (2..1000): 0
Enter first number (2..1000): 99999
Enter first number (2..1000): 2
Enter second number (2..1000): 2
Enter third number (2..1000): 2
2+2+2 Your sum is: 6