#include <iostream>
int main(int argc, char* argv[]) {
std::cout << 30000 * (5 * 30000 - 22207) / 2 + 50488389 << std::endl;
return 0;
}
The right answer I want is 1967383389, but this program outputted -180100259 after running on my computer. It seemed it had overflowed. But why? How can I judge whether an arithmetic expression will overflow?
When you compile your example code, the compiler usually throws a warning identifying exactly the part of your expression that overflows
main.cpp:4:24: warning: integer overflow in expression [-Woverflow]
std::cout << 30000 * (5 * 30000 - 22207) / 2 + 50488389 << std::endl;
~~~~~~^~~~~~~~~~~~~~~~~~~~~
Live Demo
To overcome this, use all floating point constants to do this calculation:
#include <iostream>
#include <cmath>
int main(int argc, char* argv[]) {
std::cout << std::trunc(30000.0 * (5.0 * 30000.0 - 22207.0) / 2.0 + 50488389.0) << std::endl;
// ^^ ^^ ^^ ^^ ^^ ^^
return 0;
}
Live Demo
How can I judge whether an arithmetic expression will overflow?
You can check the std::numeric_limits to see what are the maximum values, that are available with your compiler implementation and target CPU.
If you need the exact output as it was mentioned in your question, you can use I/O manipulators to bang the output in shape:
std::cout << std::fixed << std::setprecision(0)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<< std::trunc(30000.0 * (5.0 * 30000.0 - 22207.0) / 2.0 + 50488389.0) << std::endl;
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With