C++ divide by zero
c++
Solution
Yes:
In C++03
if ((x == +std::numeric_limits<float>::infinity()) ||
(x == -std::numeric_limits<float>::infinity())
)
In C++11
if (std::isinf(x))
Problem
I started to learn C++ programming and have a question about error handling. I've made a code that calculates x from the function `ax+b=0` (so I have to divide `-b` by `a`). The values are entered by users via `cin >>` If I divide by 0 i get `-int` as my output. Is it possible to catch the error (e.g. in with an `if` statement)? I know that dividing by zero is impossible and I also know that it wouldn't be a good behavior form a program, if it doesn't check the user's input (e.g. `if ((a != 0)){calculate}`). The thing is I would like to know how if/how it works to catch this error ;-) Does it depend on the hardware, operating system or compiler? My teachers couldn't help me ;) Btw. I use Eclipse Juno IDE for C/C++ on Mac OS X 10.8.2 ``` #include <iostream> #include <iomanip> using namespace std; int main() { float a, b, x; //float da Kommazahlen erwartet werden cout << "ax + b = 0" << '\n'<< endl; cout << "Bitte geben Sie einen Wert für a ein:" << endl; cin >> a; cout << "Bitte geben Sie einen Wert für b ein:" << endl; cin >> b; x = -b/a; cout << "Ergebnis:" << x << endl; if (x == #INF ) { cout << "Du bist a Volldepp - durch Null kann man nicht teilen!" << endl; } return 0; } ```