2012-12-25 41 views
-3

我有計算兩個斜率並比較它們的代碼,如果它們是相同的,我會得到它們的值。如何獲取表示未定義的值C++?

但是,如果一個斜率未定義,程序就會崩潰。我需要知道它們是否相同,即使它們未定義。我不能使用任何其他負面或正面的整數,因爲這會讓我的代碼大搞。

我更喜歡一個字的值,如5/0 =未定義,但不知道我該怎麼做。

例如:

#include <iostream> 
using namespace std; 

int r = 5/0; 

int main() 
{ 
    // Instead of crashing, this should tell me this value is undefined somehow. 
    cout << r << endl; 
    return 0; 
} 

我如何處理的情況下是斜率是完全垂直?

+0

其C++ ............ – Amadeus

+0

回覆:「請不要問我後我的代碼太長了,沒有人讀它最後一次。」其實我會要求你發佈你的代碼,否則沒有人可以做出任何合理的嘗試來回答你的問題。正是因爲它太長,所以上次沒有人讀過它。製作一個[簡短的,自包含的,正確的,可編譯的例子](http://www.sscce.org/),我們可以做得更好,爲您提供一個更好的答案,可以真正解決您的問題。 –

+1

其簡單的概念,不需要代碼 – Amadeus

回答

0

您應該以始終定義的方式(如角度)表示斜率。如果程序中有另一個步驟因數學原因未定義結果,可能會引發異常。

而且用於獲取從一個向量x的角度,y,則應該使用ATAN2 http://en.cppreference.com/w/cpp/numeric/math/atan2

double theta = atan2(y,x) ; // this is always fine 

要比較兩個角度,通過矢量X1,Y1和X2,Y2定義:

double th1 = atan2(y1,x1) 
double th2 = atan2(y1,x1) 

const double mypi=3.141592653589793238463; 

double angleDiff = pi - abs(abs(th1 - th2) - pi); 

if(angleDiff*10<=mypi){ 
    cout << " angles are within 0.1 pi (that is 18 degr) <<endl; 
} 

還要記住,比較浮點值時,除了一些特殊情況外,不應指望確切的匹配。

0

我知道這個問題是非常古老的,但因爲我試圖解決幾乎相同的問題,我決定發表一個答案。

我會建議一種方法是使用空指針來識別未定義的值。在我的情況下,使用角度是非常不準確的,因爲我正在使用gmp(gnu多精度庫),我需要完美的精度來處理從64位開始攀爬的大量位。

浮點根本不會削減它。

正如我所看到的,您有兩個選擇,一個標誌與檢索斜坡分開檢測,或者在檢索斜坡後進行檢測。 我看不出不涉及引發異常

class line { 
    bool vertical; 
    bignum slope; 

    // one method two functions 
    bool is_vertical(){return vertical;} 
    bignum slope() {return slope} 

    //alternative method 
    bignum *slope() {if (vertical) return NULL; else return &slope} 
} 

大多數代碼需要以不同方式處理一條垂直線到任何其他線路替代任何方式所以它不是一項繁重的任務,以應付在垂直線if語句

if ((slope = line.slope())==NULL){//vertical 
    // do some vertical stuff 
    cout << "line is vertical"; 
} else { 
    // do some other line stuff with bignum *slope 
    cout "slope is " << *slope; 
}