호타리 2025. 4. 23. 09:18

 

<코드>

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>

/*
 * calcOptimal: computes minimum-time profile and optionally outputs samples.
 * Suggestion: separate computation from I/O to improve testability and reuse.
 */
void calcOptimal(double v0, double vend, double vmax, double a, double dist,
    double dt, double* tr, double* ts, double* tf) {
    if (a <= 0 || dt <= 0) return;  /* validate parameters */

    /* compute accel/decel intervals */
    double tr_loc = (vmax - v0) / a;
    double dr = v0 * tr_loc + 0.5 * a * tr_loc * tr_loc;
    double tf_loc = (vmax - vend) / a;
    double df = vmax * tf_loc - 0.5 * a * tf_loc * tf_loc;
    double ts_loc;

    if (dist >= dr + df) {
        ts_loc = (dist - dr - df) / vmax;
    }
    else {
        /* triangular profile: peak < vmax */
        vmax = sqrt((2 * a * dist + v0 * v0 + vend * vend) / 2.0);
        tr_loc = (vmax - v0) / a;
        tf_loc = (vmax - vend) / a;
        ts_loc = 0.0;
        dr = v0 * tr_loc + 0.5 * a * tr_loc * tr_loc;
        df = vmax * tf_loc - 0.5 * a * tf_loc * tf_loc;
    }

    *tr = tr_loc;
    *ts = ts_loc;
    *tf = tf_loc;

    /* output phase samples */
    double t, v, d;
    /* Phase 1: accel */
    for (t = 0.0; t <= tr_loc + 1e-9; t += dt) {
        v = v0 + a * t;
        d = v0 * t + 0.5 * a * t * t;
        printf("%.1fsec: %.2f m/s, %.2f m\n", t, v, d);
    }
    /* Phase 2: cruise */
    for (t = dt; t <= ts_loc + 1e-9; t += dt) {
        printf("%.1fsec: %.2f m/s, %.2f m\n", tr_loc + t, vmax, dr + vmax * t);
    }
    /* Phase 3: decel */
    double base = tr_loc + ts_loc;
    double rem = fmax(0.0, dist - dr - df);
    for (t = dt; t <= tf_loc + 1e-9; t += dt) {
        v = vmax - a * t;
        d = dr + rem + vmax * t - 0.5 * a * t * t;
        printf("%.1fsec: %.2f m/s, %.2f m\n", base + t, v, d);
    }
}

int main(void) {
    double v0, vend, vmax, a, dist;
    /* TODO: handle invalid input and scanf failures */
    printf("출발 속도 (m/s): "); if (scanf("%lf", &v0) != 1) return 1;
    printf("도착 속도 (m/s): "); if (scanf("%lf", &vend) != 1) return 1;
    printf("최고 속도 (m/s): "); if (scanf("%lf", &vmax) != 1) return 1;
    printf("가속도/감속도 (m/s^2): "); if (scanf("%lf", &a) != 1) return 1;
    printf("거리 (m): "); if (scanf("%lf", &dist) != 1) return 1;

    double tr, ts, tf;
    const double dt = 0.1;  /* consider making dt configurable */
    calcOptimal(v0, vend, vmax, a, dist, dt, &tr, &ts, &tf);

    printf("\nResults -> tr=%.2f, ts=%.2f, tf=%.2f\n", tr, ts, tf);
    return 0;
}

 

<실행 결과>