'Why can't I set my long long variable to 1e18 + 10?

I have implemented a program in C++ and it showed a very strange bug. First of all, if I assigned my variable a like this: long long a = 1e9 + 10 and then print the value of a, it ran correctly. But if I set a to 1e18 + 10 and then print the value of a, it showed that a equals 10^18 only. Can anyone help me with this? I tried a lot but I can't understand why. Thanks. This is my code:

#include <iostream>
 
using namespace std;
 
int main() {
    long long a = 1e9 + 10;
    cout << a << endl;
    a = 1e18 + 10;
    cout << a << endl;
    return 0;
}
c++


Solution 1:[1]

1e18 is a value having type double. The presicion of type double is typically around 15 decimal digits, so adding 10 to 1e18 may not change the value of double.

You can add a cast to long long before addition to eliminate the issue in this case, but generally you should avoid using floating-point numbers to deal with integers.

#include <iostream>

int main(void) {
    long long value = static_cast<long long>(1e18) + 10;
    std::cout << value << '\n';
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MikeCAT