简体   繁体   中英

Why std::cout output overflow?

I am trying to solve the simple question on Codeforces ( round#1 question A ). For the 16th test case, my code got -270385980 which should be 27126743055556 , but on my local computer I can get the correct answer. On my computer I compiled it in GCC 4.8, and on Codeforces , I used GCC 4.7.

How could it be a negative number? Could anyone give me a hint of what is wrong with my code?

Here is my code:

#include <iostream>
#include <cmath>

int main(int argc, char *argv[]) {
    double m, n, a;
    std::cin >> m >> n >> a;
    long long res = static_cast<long>(ceil(m / a)) * static_cast<long>(ceil(n / a));
    std::cout << res;
    return 0;
}

The following number : 27126743055556 needs more than 32 bit (length of long on a 32bit processor) to be represented, so the long is overflowed and you get a negative number.

You should use long long in casting.

static_cast<long long>(ceil(m / a))

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