2010-06-01 95 views
1

我有2類:Objective-C中一條直線和一個點之間的距離?

// point : (x, y) 
@interface ICPoint : NSObject { 
    NSInteger x; 
    NSInteger y; 
} 

// line : y= ax + b 
@interface ICLine : NSObject { 
    float a; 
    float b; 
} 

而且這種方法:

// return the distance between a line and a point 
-(NSInteger) distance:(ICPoint *)point { 
    return fabs(-a*point.x +point.y - b)/sqrt(a*a + 1); 
} 

的公式似乎是正確的(根據維基百科),但結果是錯誤的,爲什麼?
謝謝!

編輯:

ICLine *line1 = [[ICLine alloc] initWithA:0.60 andB:11.25]; 
ICLine *line2 = [[ICLine alloc] initWithA:0.61 andB:-2.85]; 

ICPoint *point = [[ICPoint alloc] initWithX:41 andY:22]; 

[line1 distance:point]; // give 11, it's ok. 
[line2 distance:point]; // give 24, it should be ~0... 
+0

他們怎麼錯了? – Mark 2010-06-01 10:36:00

+0

我剛剛添加了一個例子。 – pimpampoum 2010-06-01 10:42:09

+0

你能否提供公式的來源? – swegi 2010-06-01 10:45:35

回答

1

我得到了一個獨立的實現,兩個測試應該會產生(投到NSInteger之前)〜11.87和〜0.17。因此該方法應該返回11和0,如提問者所述。

NSInteger x, y; 
float a, b; 
x = 41; y = 22; 
a = 0.61f; b = -2.85f; 
NSLog(@"result ", fabs(-a*x + y - b)/sqrt(a * a + 1)); 

表明該方法的膽量是正確的。

您的初始化程序是否正確?

+0

...我在做 - (id)initWithA:(NSInteger)a1和B:(NSInteger)b1; - (id)initWithA:(float)a1和B:(float)b1;謝謝! – pimpampoum 2010-06-01 11:11:15

+0

我已經做了太多次承認:) – 2010-06-01 11:13:40

0

公式是正確的,但你的檢查是不是。 「給24,應該是〜0 ...」你確定嗎?繪製這條線和點,你會看到它們根本不是關閉的,公式給出了正確的結果。對於這樣的測試使用您可以驗證自己的一組數據。嘗試使用標尺在紙上測量的明顯數值。

+0

這個點是(41,22),方程是y = 0.61x-2.85,對嗎? 如果在公式中我做x = 41,我得到y =〜22。所以點在線=>距離應該是0 ...不是? 我錯過了什麼? – pimpampoum 2010-06-01 11:02:58

相關問題