I have written a code to find max and min sum that can be calculated from four numbers out of five numbers in c++
but it doesn't generate the desired output on large values e.g. input I give and output I get?
I have written a code to find max and min sum that can be calculated from four numbers out of five numbers in c++
but it doesn't generate the desired output on large values e.g. input I give and output I get?
It looks like you are having overflow issues. The max value for long type is 2,147,483,647 on 32 bit systems and on Windows 64 bit (see this reference). Adding up all the values you entered gives 3,001,208,382. I am able to reproduce your error (min
is negative) on my Mac by changing long
to int
(thereby causing overflow trying to store the numbers as 32 bit values). Try changing
long a[5], max=0, min=10000, sum;
to
long long a[5], max=0, min=10000, sum; // long long is 64bit on Win
and see if you get non-negative values. Since there is no subtraction in your algorithm and you only entered positive values, the only way to get sum
to be negative is overflow.
Also, with the numbers you entered sum
will never be less than 10000
. I would suggest initializing your min and max differently. Perhaps, set min
and max
equal to sum
after the first inner loop iteration.
Use long long int
or unsigned long long int
They have higher ranges:
long long int:
-9,223,372,036,854,775,807 to 9,223,372,036,854,775,807
unsigned long long int:
0 to 18,446,744,073,709,551,615
for
without brackets are confusing.long
s work on my machine) What you want to do is read five values in input and output the min
, the max
and the sum
. There are several ways to do it.
One of the ways is to check if the values are smaller or greater than the current min/max
as you read them and add them to the sum
afterwards. You need to check if compare them to the current min/max
, not to the sum
.
if(a[i] > max)
max = a[i];
else if (a[i] < min)
min = a[i];
sum += a[i];
Another (better) way to do it is using std::valarray and use the methods it provides to retrieve what you need.
My recommandation is to start learning cpp from a better source.