Home > OS >  Can't sum a vector of integers using for loop c
Can't sum a vector of integers using for loop c

Time:03-07

I am writing a function that takes a vector of integers as input, and iterates through the vector to obtain the maximum and minimum values in the vector, as well as the sum. The maximum possible integer in the argument vector is 1000000000.

void miniMaxSum(vector<long> arr) {
    long sum = 0;
    long min = 1000000000;
    long max = 0;
    for (int i = 0; i < arr.size(); i  ) {
        cout << arr[i] << endl;
        sum  = arr[i];
        if (arr[i] < min) {
            min = arr[i];
        }
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    cout << sum << endl;
}

Using the following input vector as argument:

vector<long> x = {793810624,895642170,685903712,623789054,468592370 };

The sum is a negative number: -827229366

CodePudding user response:

long is usually a 32-bit type on most operating systems (at least 32-bit). So the maximum value it can hold is 2,147,483,647.

The sum of your numbers is 3,467,737,930. So it overflows.

Consider using unsigned long or long long (at least 64 bits) or unsigned long long for larger numbers. Or you could even use intmax_t or uintmax_t to get the biggest integer that is supported.

  • Related