⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 randwalk.cpp

📁 我学习C++ Primer Plus过程中写下的课后作业的编程代码
💻 CPP
字号:
// randwalk.cpp -- using the Vector class
// compile with the vect.cpp file
#include <iostream>
#include <cstdlib>		// rand(),srand()prototypes
#include <ctime>		// time()prototype
#include "vect.h"
#include <fstream>

int main()
{
	const int MAX = 50;
	using namespace std;
	using VECTOR::Vector;
	srand ( time(0) );	// seed random-number generator
	double direction;	
	Vector step;						// 每一步行走的方向
	Vector result ( 0.0, 0.0 );			// 每行走一步后的方向
	unsigned long steps = 0;
	double target;						// 目标距离	
	double dstep;						// 每一步行走的距离

	char filename[MAX];
	cout<<"请输入所要保存随机行走路径的文件名:";
	cin.get(filename,MAX-1);			// 文件名过长则截短到MAX-1字符
	filename[MAX-1] = '\0';
	while (cin.get() != '\n' )			
		continue;
	ofstream fout;						// 文件输出流对象
	fout.open(filename);				// 文件名与fout对象关联			
	if( !fout.is_open() )
	{
		cerr<<"Could not open file: "<<filename<<endl;
		fout.clear();
	}

	cout<<"Enter target distance (q to quit):";
	while( cin>>target )
	{
		cout<<"Enter step length: ";
		if ( !(cin>>dstep) )
			break;
		fout<<"下面是\""<<filename<<"\"的成功走出 "<<target<<" 米的艰辛路程!\n";
		fout<<"Target Distance: "<<target<<", Step Size: "<<dstep<<endl;
		while(result.magval() < target )
		{
			direction = rand()% 360;
			step.set ( dstep, direction, 'p' );
			result = result + step;
			fout<<++steps
				<<": (x,y) = ("
				<<result.xval()
				<<","
				<<result.yval()
				<<")\n";
		}
		
		cout<<"After "<<steps<<" steps,the subject "
			"has the following location: \n";
		cout<< result <<endl;
		// 输出到文件中
		fout<<"花了 "<<steps<<"步!"<<filename
			<<"才跑出距离中心"
			<<target
			<<"米"
			<<endl;
		fout<< result <<endl;

		result.polar_mode();
		cout<<" or\n"<<result<<endl;

		// 输出到文件中
		fout<<" or\n"<<result<<"\n\n\n\n\n\n\n\n\n";

		steps = 0;
		result.set( 0.0, 0.0 );
		cout<<"enter target distance (q to quit): ";
	}
	cout<<"Bye!\n";
	fout.close();		// 关闭文件
	return 0;
}

⌨️ 快捷键说明

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