はじめての C
3つの頂点の座標が
(1.0, 1.0), (5.0, 3.0), (4.0, 2.0)
の位置にある三角形の面積を求めるプログラムを作成せよ。
- /* sankaku */
- #include
- struct Point {
- float x;
- float y;
- };
- struct Triangle {
- struct Point a, b, c;
- };
- struct Triangle tri = {{1.0,1.0},{5.0,3.0},{4.0,2.0}};
- float func1(struct Triangle *); /* 関数の返り値は float 型 */
- main()
- {
- struct Triangle *ptri = &tri;
- float s;
- s = func1(&tri);
- printf("area of triangle : %f\n", s);
- }
- float func1(struct Triangle *ptri) {
- float s;
- float x1, x2, x3, y1, y2, y3;
- x1 = ptri->a.x;
- x2 = ptri->b.x;
- x3 = ptri->c.x;
- y1 = ptri->a.y;
- y2 = ptri->b.y;
- y3 = ptri->c.y;
- if ((x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1) > 0) {
- s = ((x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1)) / 2;
- } else {
- s = ((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2;
- }
- return s;
- }
text: 金山典世さん(稚内北星)のページ