简体   繁体   中英

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;
}

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 .

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 (ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM