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
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 withlong long int
. Or to make the sizes of the types more explicit, include<cstdint>
and useint64_t
.but the limits of the "long" is -2,147,483,648~2,147,483,647;
you can use
std::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.
}
as to other IDEs, maybe they do some optimization?
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.