So my code looks like this:
unsigned long i=(27984 * 619246) + (1402 * 615589);
cout<<" i= "<<i;
I don't use the variable i anywhere else etc
Output looks like this
i= 1012166658
The correct answer is 18192035842 . WHY is this happening?
So my code looks like this:
unsigned long i=(27984 * 619246) + (1402 * 615589);
cout<<" i= "<<i;
I don't use the variable i anywhere else etc
Output looks like this
i= 1012166658
The correct answer is 18192035842 . WHY is this happening?
Try this:
#include<iostream>
#include <string>
using namespace std;
int main() {
unsigned long long i = (27984ULL * 619246ULL) + (1402ULL * 615589ULL);
cout << " i= " << i;
}
using the long long
literal suffix LL
, and upgrading the type to a bigger type solves the problem.
I use the U
(unsigned) literal suffix so that we can have it the same as the resulting type.
With your original code, there was an overflow (the result did not fit in the original type, or the operator) so it returned a truncated version. An example compiler warning that I got:
warning C4307: '*': signed integral constant overflow