walk2d.cpp

来自「C++&datastructure书籍源码,以前外教提供现在与大家共享」· C++ 代码 · 共 75 行

CPP
75
字号
#include "walk2d.h"

#include <cmath>        // for sin and cos
#include "mathutils.h"  // for pi
#include "randgen.h"

RandomWalk2D::RandomWalk2D(long maxSteps,int size)
  : myPosition(),
    mySteps(0),
    myStepSize(size),
    myMaxSteps(maxSteps)
// postcondition: walker initialized    
{

}

void RandomWalk2D::TakeStep()
// postcondition: one step of random walk taken
{
    RandGen gen;                    // random number generator
    double randDirection = gen.RandReal(0,2*PI);
 
    myPosition.x += myStepSize * cos(randDirection);
    myPosition.y += myStepSize * sin(randDirection);
    mySteps++;
}

void RandomWalk2D::Init()
// postcondition: Init step of random walk taken
{
    mySteps = 0;
    myPosition = Point(0,0);
    TakeStep();
}

bool RandomWalk2D::HasMore()
// postcondition: returns false when random walk is finished
//                i.e., when # of steps taken >= max. # of steps     
//                return true if walk still in progress
{
    return mySteps < myMaxSteps;
}

void RandomWalk2D::Next()
// postcondition: next step in random walk simulated     
{
    TakeStep();
}

void RandomWalk2D::Simulate()
{
    for(Init(); HasMore(); Next())
    {
        // simulation complete using iterator methods
    }
}

long RandomWalk2D::TotalSteps() const
// postcondition: returns number of steps taken by molecule
{
	 return mySteps;
}

Point RandomWalk2D::Position() const
// postcondition: return molecule's position
{
   return myPosition;
}

Point RandomWalk2D::Current() const
// postcondition: return molecule's position
{
   return myPosition;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?