41223227 cp2023

  • Home
    • SMap
    • reveal
    • blog
  • About
  • ANSIC
  • c_ex
    • jsliu_c_programming:
    • introduce to c:
  • W16
  • W15
  • 線上繪圖
  • w13
  • w12
  • w7
  • w6
  • w5
  • 倉儲與網站評分項目
  • 期末總結
  • Brython
線上繪圖 << Previous Next >> w12

w13

// 使用標準輸入/輸出函數
#include <stdio.h>
 
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;
}



線上繪圖 << Previous Next >> w12

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