#include #include #include using namespace std;

class Vec { public: float x,y; Vec(float x_=0, float y_=0):x(x_), y(y_) {} //默认构造函数 float magnitude() //模长 { return sqrtf(xx+yy); } void show() //输出向量 { cout<<'('<<x<<','<<y<<')'<<endl; } friend Vec add(Vec a, Vec b); //向量加法 friend Vec sub(Vec a, Vec b); //向量减法 friend Vec mul(Vec a, float b); //向量数乘 friend Vec div(Vec a, float b); //向量数除 };

Vec add(Vec a, Vec b) //向量加法 { return Vec(a.x+b.x, a.y+b.y); } Vec sub(Vec a, Vec b) //向量减法 { return Vec(a.x-b.x, a.y-b.y); } Vec mul(Vec a, float b) //向量数乘 { return Vec(a.xb, a.yb); } Vec div(Vec a, float b) //向量数除 { return Vec(a.x/b, a.y/b); }

class Particle { private: Vec pos; //粒子位置 float charge; //粒子电荷 static const float K; public: Particle(Vec p=Vec(0,0), float c=0):pos(p), charge(c) {} //构造函数 Vec calcForce(const Particle& other) const //计算静电力 { Vec r = sub(other.pos, pos); //两个粒子之间的向量差 float F = Kchargeother.charge/(r.magnitude()r.magnitude()); //静电力大小 Vec Fvec = mul(r, F/r.magnitude()); //静电力向量 if(chargeother.charge>0) Fvec = mul(Fvec, -1); //同性相斥,反向 return Fvec; } };

const float Particle::K = 8.99e9;

class Field { private: vector particles; //静电场中的带电粒子 public: void addParticle(const Particle& p) //添加带电粒子 { particles.push_back(p); } Vec calcForce(const Particle& p) const //计算静电场对单个粒子的静电力 { Vec Fvec; for(auto& it: particles) { if(&p != &it) //不计算粒子对自己的作用力 { Vec F = p.calcForce(it); Fvec = add(Fvec, F); } } return Fvec; } };

int main() { //测试Vec类 Vec v1(1,2); Vec v2(3,4); v1.show(); v2.show(); Vec v3 = add(v1, v2); Vec v4 = sub(v1, v2); Vec v5 = mul(v1, 2); Vec v6 = div(v2, 2); v3.show(); v4.show(); v5.show(); v6.show();

//测试Particle类
Particle P1(Vec(1,2),0.0001),P2(Vec(2,-3),0.0002);
Vec F12 = P1.calcForce(P2);
F12.show();

//测试Field类
Field field;
field.addParticle(Particle(Vec(0,0),1e-5));
field.addParticle(Particle(Vec(1,2),2e-5));
field.addParticle(Particle(Vec(-2,1),3e-5));
Particle p(Vec(2,0),-1.5e-5);
Vec f = field.calcForce(p);
f.show();

return 0;

}

平面静电场模拟程序设计

原文地址: https://www.cveoy.top/t/topic/od0P 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录