找到在使用无限循环c++时输入的最小值

find the minimum value entered while using infinite loop c++

本文关键字:输入 最小值 c++ 无限循环      更新时间:2024-09-23

我的任务是找到用户在无限循环中应该输入的n个输入值之间的最小值,直到输入特定的数字或字符来停止循环。

我面临的问题是,我无法获得测试输入的条件,看输入的数字中哪一个最小。另外,第二个问题是,我想用char而不是int来结束循环,但我不知道这是否可能。

我在网上搜索了一下,但找不到任何答案。

旁注:我是C++的新手。我使用的是Borland C++v5.02。

#include <iostream>
#include <conio.h>
int I, min =0;
cout<<"Enter a number :";
do{
cin >> I;
if (I < min){
if (I > 0){
min = I;
}
}
}while (I > -1);
cout << min;

我使用try-catch块和stoi((解决了您的问题。

CCD_ 1用于将字符串转换为数字。如果数字输入不可转换(意味着输入了char,循环应该中断(,则const std::invalid_argument & e被捕获并自动中断循环。

#include <iostream>
using namespace std;
int main()
{
int Min = INT_MAX; string I; int x;
do
{
cout << "Enter a number or a char : ";
cin >> I; 
try
{
x = stoi(I);
if (x < Min)
{
if (x > 0) {Min = x;}
}
}
catch(const std::invalid_argument & e) {break;}
}
while(x > 0);
cout << "Minimum positive number entered : " << Min;
}

输出:

Enter a number or a char : 10
Enter a number or a char : 8
Enter a number or a char : 5
Enter a number or a char : 7
Enter a number or a char : a
Minimum positive number entered : 5

由于您的代码有点不清楚,我将两个约束都更改为I>0,您可以很容易地修改这一点。

对于带有INT_MAX的prolem,可能#include <climits>#include <limits.h>会有所帮助,如此处所述。如果问题仍然存在,解决方法是将Min设置为高值,例如10^9

*注意:运行代码::块20.03,Windows 10 64位。

代码的问题在于标头。我找不到一个可以与我的编译器Borland v5.02c++一起使用的标头,但多亏了@JerryJeremiah,他让我找到了它。

另外,我重新声明了stoi()0,因为我在循环中使用了这段代码。

代码现在对我有效。

#include <iostream>
#include <conio.h>
#include <limits.h>
int main()
{
int I, min =INT_MAX;
cout<<"Enter number of input :";
do{
cin>>I;
if (I<min ){
if(I>0){
min =I;
}
}
}while(I>-1);
cout<<min;
min =INT_MAX;
getch();
}