酷!學園
技術討論區 => 程式討論版 => C/C++程式設計討論區 => 主題作者是: Quota 於 2008-03-02 14:22
-
請教一個問題,如果我想在c++內做例外的判斷
為何我分子輸入5 分母輸入a
跑出5/2=2.5
而不是例外呢?
謝謝!
附上程式碼如下:
#include <iostream>
#include <stdlib.h>
using namespace std;
class fraction
{
private:
int numerator;
int denominator;
public:
void set_value()
{
cout << "輸入分子:";
cin >> numerator;
cout << "輸入分母:";
cin >> denominator;
}
void print_value()
{
try
{
if (denominator==0)
{
throw 0;
}
else if (denominator<0)
{
throw " ~~分母<0 這樣是不行的 ";
}
else
{
cout << numerator << "/" << denominator << "=";
cout << double (numerator)/double(denominator) << endl;
}
}
catch(int err)
{
cout <<"有問題"<<endl;
}
catch(const char* str)
{ cout <<str<<endl; }
catch(...)
{
cout <<"其他錯誤"<<endl;
}
}
};
int main()
{
fraction X;
X.set_value();
X.print_value();
system("pause");
return 0;
}
-
兩個變數在使用前沒歸零
-
5/2(5除以2)=2.5 沒錯啊,當然不會產生例外事件。
-
5/2(5除以2)=2.5 沒錯啊,當然不會產生例外事件。
可是,現在的問題是
我分母輸入a ,而不是2...
-
試試把 denominator 印出來看看?