2013-04-23 89 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