注册 登录
编程论坛 C++教室

新手求助cout的问题

obdi00 发布于 2011-03-22 11:54, 332 次点击
程序代码:
int main()
{
    TestMath MyMath;
    MyMath.Output();
}
class TestMath
{
public:
    TestMath() { }
    double Division(int A, int B)
    {
        if ( B == 0 )
            throw 0;
        else
            return (A+0.0) / B;
    }
    double Division(int A, double B)
    {
        if ( B == 0 )
            throw 0;
        else
            return (A+0.0) / B;
    }
    double Division(double A, int B)
    {
        if ( B == 0 )
            throw 0;
        else
            return (A+0.0) / B;
    }
    double Division(double A, double B)
    {
        if ( B == 0 )
            throw 0;
        else
            return (A+0.0) / B;
    }
    void Output()
    {
        double result;
        cout << "\nThe INTEGER  to INTEGER     </>      (10 / 0) = ";
        try { result = Division(10,0); }
        catch(int e) { cout << "Infinity!"; }
        cout <<result;
        cout << "\nThe INTEGER  to FLOATING    </>    (10 / 0.0) = ";
        try { result = Division(10,0.0); }
        catch(int e) { cout << "Infinity!"; }
        cout << result;
        cout << "\nThe FLOATING to INTEGER     </>    (10.0 / 0) = ";
        try { result = Division(10.0,0); }
        catch(int e) { cout << "Infinity!"; }
        cout << result;
        cout << "\nThe FLOATING to FLOATING    </>  (10.0 / 3.0) = ";
        try { result = Division(10.0,3.0); }
        catch(int e) { cout << "Infinity!"; }
        cout << result;
    }
private:
};

很难看的码……大家就原谅一下

cout的时候如果前一个是除0, 后面的cout如果有除0, 会打出"Infinity!", 但是会在后面跟上前一个不是除0的结果。 这个要怎么改啊?
2 回复
#2
buffer2011-03-22 12:40
把cout <<result;放到try块里面,像这样:
程序代码:
try { result = Division(10,0);
            cout <<result;
            }
        catch(int e) { cout << "Infinity!"; }
        
#3
obdi002011-03-22 13:19
谢谢buffer, 问题解决了!!
1