[英]How to Find Max and Min values?
#include<iostream>
main()
{
int limit,input;
int sum=0;
int i;
std::cout<<"Please Enter the limit: ";
std::cin>>limit;
for(i=0;i<limit;i++)
{
std::cout<<"Please Input values: ";
std::cin>>input;
sum+=input;
}
std::cout<<"The sum of the values is: "<<sum;
std::cout << std::endl;
std::cout<<"The average of the values is: "<<sum/1+i;
}
What to do if i want to find Max and Min Values from the values input by the user? 如果我想从用户输入的值中找到最大值和最小值,该怎么办?
Try this 尝试这个
int min_v = std::numeric_limits<int>::max();
int max_v = std::numeric_limits<int>::min();
for(i=0;i<limit;i++)
{
std::cout<<"Please Input values: ";
std::cin>>input;
sum+=input;
min_v = std::min(input, min_v);
max_v = std::max(input, max_v);
}
There are multiple ways, You can store all values input from user into a std::vector<int>
. 有多种方法,您可以将用户输入的所有值存储到
std::vector<int>
。 Use this vector to find out sum of elements and then sort it using std::sort
to get Max and Min values as well. 使用此向量找出元素的总和,然后使用
std::sort
对其进行std::sort
以获取最大值和最小值。 Simple! 简单!
vector<int> v(limits);
for(int i = 0; i<limits; i++)
{
int input;
cin >> input;
v.push_back(input);
}
int sum = 0;
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
sum += *it;
}
cout << "sum = " << sum << endl;
sort(v.begin(), v.end());
cout << "Min = " << v[0] << endl;
cout << "Max = " << v[v.size() -1] << endl;
Generally you need to do the following: 通常,您需要执行以下操作:
Max
and Min
values. Max
和Min
。 Min
with a very big value, eg 2147483647, and Max
to a very small value, eg -2147483648. Min
,然后将Max
初始化一个很小的值(例如-2147483648)。 input
with Min
, if input
is smaller than Min
, update Min
. input
与Min
进行比较,如果input
小于Min
,则更新Min
。 Do the reverse with Max
. Max
相反。 That's it. 而已。
Please try the code below. 请尝试下面的代码。
int main()
{
int limit,input;
int sum=0;
int i;
std::cout<<"Please Enter the limit: ";
std::cin>>limit;
int min = 0;
int max = 0;
for(i=0;i<limit;i++)
{
std::cout<<"Please Input values: ";
std::cin>>input;
if(i == 0)
{
min = input;
max = input;
}
else
{
if(input < min)
min = input;
if(input > max)
max = input;
}
sum+=input;
}
std::cout<<"The sum of the values is: "<<sum<<std::endl;
std::cout<<"The average of the values is: "<<sum/(1+i)<<std::endl;
std::cout<<"Max: "<<max<<std::endl;
std::cout<<"Min: "<<min<<std::endl;
return 0;
}
int max=0, min=0;
for(i=0;i<limit;i++)
{
std::cout<<"Please Input values: ";
std::cin>>input;
sum+=input;
if(i==0){
max=input;
min=input;
}
if(input>max)
max=input;
if(input<min)
min=input;
}
Now, you got the max and min value.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.