(我們的星星)3.0 – 測試程序示例
前面已經有了源碼,這邊就放一個測試程序
#include<iostream>//輸入輸出流
#include<time.h>//時間
#include<vector>//vector容器
#include<starx.h>//我們的星星類頭文件
#include<fstream>//文件讀寫流
using namespace std;//引用命名空間std
void Write2file(ofstream& output, const double &data)
{
output<<data<<endl;
}
//void cd(const starx& g){
// g.speed(x);
//}
int main()
{
/*準備三個文件流用以存放座標數據*/
ofstream output1x("D:\\Lists\\Matlab\\application\\movedatax.txt",ofstream::out|ofstream::trunc);
ofstream output1y("D:\\Lists\\Matlab\\application\\movedatay.txt",ofstream::out|ofstream::trunc);
ofstream output2x("D:\\Lists\\Matlab\\application\\movedata2x.txt",ofstream::out|ofstream::trunc);
ofstream output2y("D:\\Lists\\Matlab\\application\\movedata2y.txt",ofstream::out|ofstream::trunc);
ofstream output3x("D:\\Lists\\Matlab\\application\\movedata3x.txt",ofstream::out|ofstream::trunc);
ofstream output3y("D:\\Lists\\Matlab\\application\\movedata3y.txt",ofstream::out|ofstream::trunc);
/* 定義三顆星星 */
starx xx2(2,3,0,-18,1);//(0,1.3)位置 初始速度(0,-1)質量1
starx xx(0,0,0,-18,1);//(0,1)位置 初始速度(0,-1)質量1
starx t0(1,0,0,0,50);
/*設置計時器(作爲時間基準,參考頭文件<time.h>)*/
clock_t now;
double dtime=0;
now = clock();//zero = now;
int tt=0;
while(tt<70000)//計算星星們的座標70000次
{
/* 當時間變化可見時 (避免循環間隔過短造成計算次數不足)*/
if(now != clock())
{
/* 指明受力集合 */
vector<starx> stx1={t0};//xx受力來源
vector<starx> stx2={t0,xx};
vector<starx> stx3={xx,xx2};
dtime = ((double)(clock()-now))/CLK_TCK;
/* 計算上一個時間間隔的位移 */
xx.kinesis(dtime);
xx2.kinesis(dtime);
//t0.kinesis(dtime);
/*計算受力(實際上是合力)*/
xx.gravitation(stx1);
xx2.gravitation(stx2);
//t0.gravitation(stx3);
/*加速度*/
xx.accelerate();
xx2.accelerate();
//t0.accelerate();
/* 速度 */
xx.velocity(dtime);
xx2.velocity(dtime);
//t0.velocity(dtime);
now = clock();
tt++;
cout<<"location:"<<xx.location(x)<<","<<xx.location(y)
<<"\tvelocity:"<<xx.speed(y)
<<"\tforce:"<<xx.force(x)<<","<<xx.force(y)<<endl;
//記錄x、y座標到對應文件中
Write2file(output1x,xx.location(x));
Write2file(output1y,xx.location(y));
Write2file(output2x,xx2.location(x));
Write2file(output2y,xx2.location(y));
Write2file(output3x,t0.location(x));
Write2file(output3y,t0.location(y));
}
}
now = clock();
//cout<<"run time:"<<(double)(now-zero)/CLK_TCK<<endl;
return 0;
}
然後使用matlab繪製軌跡曲線
- 代碼如下:
%分析平面物理模型的數據
%載入數據
load movedatax.txt;
load movedatay.txt;
load movedata2x.txt;
load movedata2y.txt;
load movedata3x.txt;
load movedata3y.txt;
data1x = movedatax;
data1y = movedatay;
data2x = movedata2x;
data2y = movedata2y;
data3x = movedata3x;
data3y = movedata3y;
%構建x軸離散點 --與data等長
%xis = 1:length(data);
%繪製散點圖
%plot(xis,data,'x');
%hold on;
%subplot(1,2,2);
%format;
hold on;
plot(data1x,data1y);
plot(data2x,data2y);
plot(data3x,data3y);%平滑曲線方便觀察數據特徵
title("質點運動軌跡(70000點數據)");
xlabel("x座標");
ylabel("y座標");
% hold on;
plot(2,3,'bx');
plot(0,0,'rx');
plot(1,0,'gx');
看看結果
放大看看
ok
準備工作(類的設計思路&頭文件):https://blog.csdn.net/qq_33904382/article/details/102757667
類源文件(.cpp):
https://blog.csdn.net/qq_33904382/article/details/102789576