c++ - How I can stop the " while loop " if the user enter number <0?
问题描述
in this example :
int numbers=0 ,sum=0;
while (numbers >=0)
{
cout<<"Enter positive numbers: ";
cin>>numbers;
sum += numbers;
}
cout<<"The result = "<<sum<<"\n";
Can u help me what I should to do please?
解决方案
In the loop, you'll have to deal with two situations.
- The user enters invalid input or EOF.
- The user enters a number less than 0.
For the first, you'll need to use:
if ( cin >> numbers )
{
// Reading to numbers was successful.
}
else
{
// Deal with the error.
}
For the second situation, you'll need to use:
if ( numbers < 0 )
{
break;
}
Put it all together,
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";
推荐阅读
- nvidia - RuntimeError:[HCDEBUG][ERROR] 运行时错误:无效的设备 ID:2 /raid/user/hugectr/HugeCTR/src/resource_managers/resource_manager_core.cpp:47
- javascript - Highcarts - 让日期时间 xaxis 在某个月份开始
- c# - unicode 大写在 .NET6 中工作的先决条件是什么?
- python - 使用带有条件的 for 循环创建多个数据框
- vue.js - 选择带有自定义标签的单选按钮
- nginx - Nginx 仅适用于 80 以外的端口
- python - Python:通过对新行的列值进行采样来生成合成数据
- c# - Can't get query parameter from HttpRequestData
- python - 需要将python文件导入机器人文件
- python - AppIndicator 在登录时启动的系统条件