#include <stdio.h>

struct point2d {                /* 2次元空間の点のx座標とy座標をそれぞれdoubleに格納 */
    double x, y;
};

struct linesegment {            /* 線分の始点sと終点eをそれぞれstruct point2dに格納 */
    struct point2d s, e;
};

/* 交点判定 (1:交わる、0:交わらない) */
int if_intersect(struct linesegment line1, struct linesegment line2)
{
    double m[2];                /* 傾き                 */
    int f_mv[2];                /* y軸と平行かのフラグ  */
    struct point2d kt;          /* 交点                 */

    /* 傾き */
    f_mv[0] = (line1.e.x == line1.s.x) ? 1 : 0;
    if (f_mv[0] == 0) {
        m[0] = (line1.e.y - line1.s.y) / (line1.e.x - line1.s.x);
    }
    f_mv[1] = (line2.e.x == line2.s.x) ? 1 : 0;
    if (f_mv[1] == 0) {
        m[1] = (line2.e.y - line2.s.y) / (line2.e.x - line2.s.x);
    }
    /* 平行か？ */
    if (f_mv[0] == 1 && f_mv[1] == 1) {
        return 0;
    }
    if (f_mv[0] == 0 && f_mv[1] == 0) {
        if (m[0] == m[1]) {
            return 0;
        }
    }
    /* 交点計算 */
    if (f_mv[0] == 0 && f_mv[1] == 0) {
        kt.x = (m[0] * line1.s.x - line1.s.y - m[1] * line2.s.x + line2.s.y) / (m[0] - m[1]);
        kt.y = m[0] * kt.x - m[0] * line1.s.x + line1.s.y;
    } else if (f_mv[0]) {
        kt.x = line1.s.x;
        kt.y = m[1] * line1.s.x - m[1] * line2.s.x + line2.s.y;
    } else if (f_mv[1]) {
        kt.x = line2.s.x;
        kt.y = m[0] * line2.s.x - m[0] * line1.s.x + line1.s.y;
    }
    /* 交点が線分の範囲内か判定 */
    if (f_mv[0]) {
        if (line1.s.y < line1.e.y) {
            if (line1.s.y <= kt.y && kt.y <= line1.e.y) {
                return 1;
            }
        } else {
            if (line1.e.y <= kt.y && kt.y <= line1.s.y) {
                return 1;
            }
        }
    }
    if (f_mv[1]) {
        if (line2.s.y < line2.e.y) {
            if (line2.s.y <= kt.y && kt.y <= line2.e.y) {
                return 1;
            }
        } else {
            if (line2.e.y <= kt.y && kt.y <= line2.s.y) {
                return 1;
            }
        }
    }
    if (f_mv[0] == 0 && f_mv[1] == 0) {
        if (line1.s.x < line1.e.x) {
            if (line1.s.x <= kt.x && kt.x <= line1.e.x) {
                return 1;
            }
        } else {
            if (line1.e.x <= kt.x && kt.x <= line1.s.x) {
                return 1;
            }
        }
    }
    return 0;
}

/*  main        */
int main()
{
    struct linesegment line1 = {
        {0.0, 0.0},
        {2.0, 1.0}
    };
    struct linesegment line2 = {
        {1.0, 2.0},
        {1.5, 0.0}
    };

    printf(
        "線分 [%f, %f]-[%f, %f]\n"
        "と   [%f, %f]-[%f, %f]\n"
        "は、交わ%s\n"
        , line1.s, line1.e, line2.s, line2.e
        , if_intersect(line1, line2) ? "る" : "らない"
    );
    return 0;
}
