C++除以零

use*_*132 2 c++

我开始学习C++编程,并对错误处理有疑问.

我做了从函数计算x代码ax+b=0(所以我必须要划分-ba).用户通过输入值cin >>

如果我除以0,我得到-int我的输出.是否有可能捕获错误(例如在if声明中)?

我知道除以零是不可能的,我也知道如果不检查用户的输入(例如if ((a != 0)){calculate}),它不会是一个好的行为形成一个程序.问题是我想知道如何/如何捕获此错误;-)它是否依赖于硬件,操作系统或编译器?

我的老师帮不了我;)

顺便说一句.我在Mac OS X 10.8.2上使用Eclipse Juno IDE for C/C++

#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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 7

是:

在C++ 03中

 if ((x == +std::numeric_limits<float>::infinity()) || 
     (x == -std::numeric_limits<float>::infinity())
    )
Run Code Online (Sandbox Code Playgroud)

在C++ 11中

 if (std::isinf(x))
Run Code Online (Sandbox Code Playgroud)