skip to Main Content

Code:

#include <iostream>

using namespace std;

long ar[10];
int arraySize;

long aVeryBigSum(long arr[]) {
    long total = 0;

    for (int x = 0; x < arraySize; x++) {
    
        total += ar[x];
    }
    return total;
}

int main() {
    
    cin >> arraySize;
    for (int x = 0; x < arraySize; x++) {

        cin >> ar[x];   
    }
    cout << aVeryBigSum(ar);

return 0;
}
 

Input:

5
1000000001 1000000002 1000000003 1000000004 1000000005

Visual Studio output:

705032719

Online IED output(correct):

5000000015 

I have no idea what to try in this situation as different compilers are giving me different answer. Assuming its something to do with data type long

3

Answers


  1. Your long int is likely a signed 32-bit integer type, which means the largest positive integer it can store is 2,147,483,647, but your sum adds up to 5,000,000,015. Because this is larger, integer overflow has occurred.

    Replace the long int type with long long int. Or to make the sizes of the types more explicit, include <cstdint> and use int64_t.

    Login or Signup to reply.
  2. but the limits of the "long" is -2,147,483,648~2,147,483,647;
    you can usestd::numeric_limits<long>::max();to get the limit.
    the value total has exceeded its limits since the third addition,so the outcome was not as your expectation.
    change the long to "long long" you’ll get the correct answer.

    long long aVeryBigSum(long arr[]) {
    long long total = 0;
    
    for (int x = 0; x < arraySize; x++) {
    
        total += ar[x];
    }
    return total;
    

    }

    as to other IDEs, maybe they do some optimization?

    Login or Signup to reply.
  3. this problem is associated with specifical compilers and machines. c++ standard just promises that the length of int is not shorter than short, the length of long is not shorter than int, the length of long long is not shorter than long.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search