はじめての C

3つの頂点の座標が
(1.0, 1.0), (5.0, 3.0), (4.0, 2.0)
の位置にある三角形の面積を求めるプログラムを作成せよ。

  1. /* sankaku */
  2. #include
  3. struct Point {
  4. float x;
  5. float y;
  6. };
  7. struct Triangle {
  8. struct Point a, b, c;
  9. };
  10. struct Triangle tri = {{1.0,1.0},{5.0,3.0},{4.0,2.0}};
  11. float func1(struct Triangle *); /* 関数の返り値は float 型 */
  12. main()
  13. {
  14. struct Triangle *ptri = &tri;
  15. float s;
  16. s = func1(&tri);
  17. printf("area of triangle : %f\n", s);
  18. }
  19. float func1(struct Triangle *ptri) {
  20. float s;
  21. float x1, x2, x3, y1, y2, y3;
  22. x1 = ptri->a.x;
  23. x2 = ptri->b.x;
  24. x3 = ptri->c.x;
  25. y1 = ptri->a.y;
  26. y2 = ptri->b.y;
  27. y3 = ptri->c.y;
  28. if ((x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1) > 0) {
  29. s = ((x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1)) / 2;
  30. } else {
  31. s = ((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2;
  32. }
  33. return s;
  34. }

text: 金山典世さん(稚内北星)のページ