找到在使用无限循环c++时输入的最小值
find the minimum value entered while using infinite loop c++
我的任务是找到用户在无限循环中应该输入的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();
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用递归的数组的最小值.这是怎么回事
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 从C++的用户输入中查找最小值
- 如何正确找到用户输入的最小值
- 将最大最小值的数据与可变数量的输入进行比较 C++
- 如何打印用户在C++中输入的 10 个数字的最小值
- 显示将来自用户输入的数组的最小值和最大值
- 试图通过函数查找数组的最大值和最小值,其中数组值由用户输入
- 在C++中,我需要创建一个程序,该程序在输入某个数字时循环并停止,然后显示最大值和最小值
- 如何将用户输入的最小值限制为流大小减去一位
- 需要帮助在填充了用户输入的向量中搜索最小值
- 通过用户输入查找c++中的最大值和最小值
- 查找输入值的平均值、最大值和最小值
- C++循环查找用户输入的最小值、最大值、平均值和总和
- 如何计算用户输入列表的最大值、最小值和平均值