-6

I have written a code to find max and min sum that can be calculated from four numbers out of five numbers in c++

code

but it doesn't generate the desired output on large values e.g. input I give and output I get?

image

Chandresh Khambhayata
  • 1,748
  • 2
  • 31
  • 60
  • 2
    It would be best if you would put the code and output into the question. Then people can copy/paste the code and look at it. – nalyd88 Aug 26 '17 at 05:18
  • 3
    Please paste the formatted code in the original question. – DYZ Aug 26 '17 at 05:20
  • 3
    You also should work on your code alignment. I'm sure there are bugs that you just missed because of your horrible code alignment. – Artemy Vysotsky Aug 26 '17 at 05:21

3 Answers3

1

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.

nalyd88
  • 4,940
  • 8
  • 35
  • 51
0

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

Manjunath
  • 491
  • 2
  • 6
  • 17
0
  1. The way your code is aligned is ugly and error prone.
  2. Those for without brackets are confusing.
  3. It is probably not an onverflow. (longs work on my machine) ssoguy.png

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.

Nhatz HK
  • 42
  • 2
  • 11