2013-04-23 91 views
0

在這裏得到了一些代碼給我一個運行時錯誤,我似乎無法修復。函數Length()計算點數組中所有點之間的累積距離。它使用一個先前定義的函數Distance(),我知道它完美地工作。任何指針?運行時錯誤問題

這裏是功能我的源代碼:

template<typename Point>    //Length function 
double PointArray<Point>::Length() const 
{ 
    double total_length = 0; 
    for (int i=0; i<Size(); i++) 
    { 
     total_length += (GetElement(i)).Distance(GetElement(i+1)); 
    } 
    return total_length; 
} 

這裏是我的實現:

cout<<"The Length of the Point Array is: "<<(*ptArray1).Length()<<endl; 

非常感謝!

回答

3

您正在閱讀超出數組末尾的元素。

for (int i=0; i<Size(); i++) 
{ 
    total_length += (GetElement(i)).Distance(GetElement(i+1)); 
                 //^^^ 
} 

一個到達for環你讀的最後一個元素,然後計算從下一個元件的距離的端部 - 這是陣列的邊界之外。你for循環應該是這個樣子:

for (int i=0; i<Size() - 1; i++) 
{ 
    total_length += (GetElement(i)).Distance(GetElement(i+1)); 
} 
+0

哇。永遠不會想到這一點。非常感激! – Byron 2013-04-23 13:30:28

2

試試這個:

template<typename Point>    //Length function 
double PointArray<Point>::Length() const 
{ 
    double total_length = 0; 
    for (int i=0; i<Size()-1; i++) 
    {    //^^^ otherwise, i+1 will be out of range 
     total_length += (GetElement(i)).Distance(GetElement(i+1)); 
    } 
    return total_length; 
} 
+0

+1!最後在你之前得到一個。 – 2013-04-23 02:55:01

+0

@CaptainObvlious你很有趣。但是謝謝! – taocp 2013-04-23 02:55:54