user10314846
user10314846

Reputation:

unexpected results of division and Modulus in c++

why 990099009900 / 10 equals to -203843547 in c++?

#include <iostream>
using namespace std;
int main()
{
    long int n = 990099009900;
    cout << n / 10;
}

Upvotes: 0

Views: 52

Answers (2)

Blaze
Blaze

Reputation: 16876

If you run this here:

std::cout << "limit " << std::numeric_limits<long int>::max();

You probably get 2147483647, like how it happens on Visual Studio. Try long long instead:

#include <iostream>
int main()
{
    long long n = 990099009900;
    std::cout << n / 10;
}

This is guaranteed to be at least 64 bit, while long int isn't (that's at least 32 bit). 32 bits aren't enough to hold 990099009900.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234875

You need to use a long long for a number of that size in order for your code to be portable.

You are using a system where your LONG_MAX (i.e. std::numeric_limits<long>::max()) is smaller than 990099009900.

This flexibility has its drawbacks which is one reason why the fixed width types like std::int64_t were introduced.

Another approach is to use

auto n = 990099009900;

and let the compiler figure it out, although that can cause problems if you're close to the limit of the type, and you increase n.

Upvotes: 1

Related Questions