41223209 cp2023

  • Home
    • SMap
    • reveal
    • blog
  • About
  • w5
  • w6
  • w7
  • w12
  • w13
  • w15
  • w16
  • ANSIC
  • c_ex
  • 教學影片
  • 倉儲與網站評分項目
  • Brython
w12 << Previous Next >> w15

w13

// 為了使用print
#include <stdio.h>

// main() { 為整個程式執行的開頭,加上int以回傳結果
int main() {
    // 輸出名為motion_data.txt的檔案
    FILE *outputFile = fopen("motion_data.txt", "w");
    if (!outputFile) {
        fprintf(stderr, "Failed to create data file.\n");
        return 1;
    }

    // 模擬運動10秒並計算位移和速度,同時將資料寫入文件
    double x = 0.2;  // 初始位移
    double v = 0.0;  // 初始速度
    double dt = 0.01; // 時間步長
    double t = 0.0;  // 時間

    while (t <= 10.0) {
        double acceleration = (-10.0 * x - 0.5 * v) / 1.0; // 此處修改系統參數
        v += acceleration * dt;
        x += v * dt;

        fprintf(outputFile, "%lf %lf %lf\n", t, x, v);

        t += dt;
    }

    // 關閉資料檔案
    fclose(outputFile);

    FILE *gnuplotPipe = popen("gnuplot -persistent", "w");
    if (!gnuplotPipe) {
        fprintf(stderr, "Failed to start Gnuplot.\n");
        return 1;
    }

    
    fprintf(gnuplotPipe, "set terminal pngcairo enhanced font 'default,10' size 800,400\n");
    // 在images資料夾輸出名為motion_plot.png的檔案
    fprintf(gnuplotPipe, "set output './../images/motion_plot.png'\n");
    fprintf(gnuplotPipe, "set title 'Displacement and Velocity vs. Time'\n");
    fprintf(gnuplotPipe, "set xlabel 'Time (s)'\n");
    fprintf(gnuplotPipe, "set ylabel 'Displacement (m)'\n");
    fprintf(gnuplotPipe, "plot 'motion_data.txt' using 1:2 with lines lw 2 title 'Displacement', \
                             'motion_data.txt' using 1:3 with lines lw 2 title 'Velocity'\n");

    // 關閉 Gnuplot 進程
    fprintf(gnuplotPipe, "exit\n");
    pclose(gnuplotPipe);

    return 0;
}


w12 << Previous Next >> w15

Copyright © All rights reserved | This template is made with by Colorlib