programme crashes after returning result.

I'm just curious why my application actually crashes after it compute the area of a cross.

I output is correct but it crashes after it calculation is done.

cross.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
void Cross::setCrossCord()
{
    for (int i=0; i<=12; i++)
    {
        cout << "Please enter x-ordinate of pt " << i+1 << ": "; 
        cin >> xVal;
        xvalue[i] = xVal;
        cout << endl;
        cout << "Please enter y-ordinate of pt " << i+1 << ": ";
        cin >> yVal;
        yvalue[i] = yVal;
        cout << endl;
    }
}


double Cross::computeArea()
{
    int points = 12;
    int running_total = 0;

    for (int i=0; i<12-1; i++)
    {
      running_total = (xvalue[i]*yvalue[i+1]) - (xvalue[i+1]*yvalue[i]);  //cross calculation of coord in a cross 
    }                                                                     //(x1*y2)-(y1*x1)

    running_total = (xvalue[points-1]*yvalue[0]) - (xvalue[0]*yvalue[points-1]);   // traverse back to the origin point
                                                                                   // (xn*y1)-(yn*x1)

    area = abs(running_total / 2); //purpose of absolute is to make sure result is positive. 
                                  //polygon are specified in counter-clockwise order (i.e. by the right-hand rule), then the area will be positive.

    return (area);
}

int main()
{
    Cross cross;
    string shapetype;

    cout << "enter shape type: " << endl;
    cin >> shapetype;

    if(shapetype == "cross")
    {
    cross.setCrossCord();
    }else
    {cout << "error" << endl;};

    cout << "area of cross is: " << cross.computeArea() << endl;
    return 0;
}


how ever if i change my for loop to this
for(int i=0; i<12; i++)
the calculation would actually be wrong.. why is this so?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void Cross::setCrossCord()
{
    for (int i=0; i<=12; i++) // if xvalue and yvalue are length 12, i must be < 12 here
    {
        cout << "Please enter x-ordinate of pt " << i+1 << ": "; 
        cin >> xVal;
        xvalue[i] = xVal;
        cout << endl;
        cout << "Please enter y-ordinate of pt " << i+1 << ": ";
        cin >> yVal;
        yvalue[i] = yVal;
        cout << endl;
    }
}


I don't think you get correct output.

In computeArea, running_total isn't actually a running total.

It is always set to (xvalue[points-1]*yvalue[0]) - (xvalue[0]*yvalue[points-1]);

So you are saying the area of a cross can be calculated from only the first and last coordinates.
Last edited on
Topic archived. No new replies allowed.