Max and MIn values

How can find the max and min values from input that the user enters


#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;


}
Create a var for min and max.
Set the first number that the user inputs as max and also as min.
For the remaining numbers you check if the number is greater that set it as new max. If it is smaller than set it as new min.
The last line is wrong for several reasons. Since division has higher precedence than addition, sum/1+i means (sum/1)+i, so I think you meant sum/(1+i)

But that isn't right. If you enter 3 values then the value of i will be 3 when you exit the loop, so the average is actually sum/i.

But that still isn't right because both sum and i are integers, so the compiler will do integer division and truncate the result. For example, if you enter numbers 2 and 3, it will compute 5/2 and get 2, which isn't the average. To fix this, you cast one number to a double:
static_cast<double>sum / i. This will convert sum to a double. Then the compiler will automatically convert i to a double before dividing. The result is a double.
Topic archived. No new replies allowed.