在此示例中:
int numbers=0 ,sum=0;
while (numbers >=0)
{
cout<<"Enter positive numbers: ";
cin>>numbers;
sum += numbers;
}
cout<<"The result = "<<sum<<"\n";
您能帮我做什么吗?
答案 0 :(得分:3)
在循环中,您将不得不处理两种情况。
首先,您需要使用:
if ( cin >> numbers )
{
// Reading to numbers was successful.
}
else
{
// Deal with the error.
}
对于第二种情况,您需要使用:
if ( numbers < 0 )
{
break;
}
将它们放在一起,
while ( true )
{
cout << "Enter positive numbers: ";
if ( cin >> numbers )
{
if ( numbers < 0 )
{
break;
}
}
else
{
// Deal with error. Perhaps break out of the loop too?
break
}
sum += numbers;
}
cout << "The result = " << sum << "\n";
答案 1 :(得分:0)
您可以添加:
if (numbers < 0) {
return;
}