0
点赞
收藏
分享

微信扫一扫

C++漫步者问题模拟

#include <iostream>



#include <string>



#include <cmath>



#include <cstdlib>



#include <ctime>



using namespace std;






//随机漫步问题






class Vector



{



private:


double mag;//极坐标长度


double dir;//极坐标方向



public:


Vector();


Vector(double m,double d);


double magval()


{


return mag;


}


double dirval()


{


return dir;


}


Vector operator+(const Vector &v)


{


//先化作直角坐标


float x=mag*cos(dir);


float y=mag*sin(dir);





float v_x=v.mag*cos(v.dir);


float v_y=v.mag*sin(v.dir);





float x_total=x+v_x;


float y_total=y+v_y;





return Vector(sqrt((x_total*x_total+y_total*y_total)),atan2(y_total,x_total));


}






};



Vector::Vector()



{


mag=0;


dir=0;



}



Vector::Vector(double m,double d)



{


mag=m;


dir=d;



}



int main()



{


srand(time(0));


Vector result(0.0,0.0);


double direction;


int steps=0;


//直至漫步到距离为50的地方才停止


while(result.magval()<50)


{


//随机生成指定步数的向量


direction=rand()%360;


Vector temp(2,direction);


//走一步


result=result+temp;


steps++;


}


cout<<"steps="<<steps<<endl;





return 0;



}

举报

相关推荐

0 条评论