Wrong area calculation objective-c?

可紊 提交于 2020-01-06 23:50:25

问题


I have an array with 5 CGPoints (v0, v1, v2, v3, v4) which are the vertex of the shape implemented like this:

_arrayVertex = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithCGPoint:v0], [NSValue valueWithCGPoint:v1], [NSValue valueWithCGPoint:v2], [NSValue valueWithCGPoint:v3], [NSValue valueWithCGPoint:v4], nil];

Then, I calculate the area with those points:

- (float)calculateArea {

    float area = 0;
    int N = (int)_arrayVertex.count;

    for (int i = 0; i < N-1; i++) {

        float term = ([_arrayVertex[i] CGPointValue].x * [_arrayVertex[i+1 % N] CGPointValue].y -
                  [_arrayVertex[i+1 % N] CGPointValue].x * [_arrayVertex[i] CGPointValue].y)/2.0;

        area += term;
    }

    return fabsf(area);

}

Is the area correctly calculated? Am I missing something?. Thank you in advance.


回答1:


sbim:

- (float)calculateArea {

    float area = 0;
    int N = (int)_arrayVertex.count;

    for (int i = 0; i < N; i++) {

        float term = ([_arrayVertex[i] CGPointValue].x * [_arrayVertex[(i+1) % N] CGPointValue].y -
              [_arrayVertex[(i+1) % N] CGPointValue].x * [_arrayVertex[i] CGPointValue].y)/2.0;

        area += term;
    }

    return fabsf(area);

} 


来源:https://stackoverflow.com/questions/35649172/wrong-area-calculation-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!