编程练习11.9
1.修改程序清单 11.5,使之将一系列连续的随机漫步者位置写入到文件中。对于每个位置,用步号进行标示。另外,让该程序将初始条件(目标距离和步长)以及结果小结写入到该文件中。该文件的内容与下面类似:
Target Distance:100,stepSize:20
0:(xy)=(0,0)
1:(x,y)=(-11.4715,16.383)
2:(x,y)=(-8.68807,-3.42232)
26:(x,y)=(42.2919,-78.2594)
27:(x,y)=(58.6749,-89.7309)
After 27 steps,the subject has the following location:
(x,y)=(58.6749,-89.7309)
or
(m,a)=(107.212,-56.8194)
Average outward distance perstep=3.97081
vector.h
#pragma once
//vect.h -- Vector class with <<,mode state
#ifndef VECTOR_H_
#define VECTOR_H_
#include<iostream>
namespace VECTOR
{
class Vector
{
public:
enum Mode {
RECT, POL };//以此为直角坐标,极坐标(长度,角度)
//RECT for rectangular,POL for Polar modes
private:
double x;//horizontal value x方向x坐标
double y;//vertical value y方向y坐标
double mag; //length of value 极坐标的长度
double ang;//direction of vector in degrees,极坐标的角度
Mode mode;//RECT or POL
//private methods for setting values
void set_mag();
void set_ang();
void set_x();
void set_y();
public:
Vector();
Vector(double x, double y, Mode form = RECT);
void reset(double x, double y, Mode form = RECT);
~Vector();
double xval()const {
return x; }//report x val
double yval()const {
return y; }//report y val
double magVal()const {
return mag; }//report magnitude
double angval()const {
return ang; }//report angle
void polar_mode();//set mode to POL
void rect_mode();//set mode to RECT
//operator overloading
Vector operator+(const Vector& b)const;
Vector operator-(const Vector& b)const;
Vector operator-()const;
Vector operator*(double n)const;
//friends
friend Vector operator*(double n, const Vector& a);
friend std::ostream& operator<<(std::ostream& os, const Vector& v)