Tutorial: Object-Oriented Programming using C++ Tutorial: robot.
h
! Define an object to represent the position of a mobile robot on a 2- #define PI 3.14159265
dimensional grid and the direction in which it is facing.
! Write a constructor method. class robot {
! Write methods to move the robot forwards and backwards by a private:
certain distance. double x;
! Write a method to rotate the robot clockwise by a certain number double y;
of degrees. double r; // rotation clockwise wrt due north
! Write a method to print the position and orientation of the robot. public:
! Write a test program that makes the robot traverse a rectangle robot ();
and return to its starting point. The program should print the void forwards (double distance);
position of the report after each movement. void backwards (double distance);
void rotate (double degrees);
void print_position ();
Hint: the following can be used to calculate sine and cosine where x (a };
double) is in degrees:
#define PI 3.14159265
#include <math.h>
sin(x * PI / 180.0)
cos(x * PI / 180.0)
Tutorial: robot.cpp Tutorial: robotMain.cpp
#include <iostream.h> #include "robot.h"
#include <math.h> void main()
#include "robot.h"
{
robot::robot ()
{ robot myRobot;
x = 0.0; myRobot.print_position();
y = 0.0; // up
r = 0.0; myRobot.forwards(100);
} myRobot.print_position();
void robot::forwards (double distance)
// right
{
x += distance * sin(r * PI / 180.0); myRobot.rotate(90);
y += distance * cos(r * PI / 180.0); myRobot.forwards(200);
return; myRobot.print_position();
} // down
void robot::backwards (double distance) myRobot.rotate(-90-360);
{
x -= distance * sin(r * PI / 180.0);
myRobot.backwards(50);
y -= distance * cos(r * PI / 180.0); myRobot.backwards(50);
return; myRobot.print_position();
} // left
void robot::rotate (double degrees) myRobot.rotate(-90+360*2);
{ myRobot.forwards(200);
r += degrees;
if ((r >= 360) || (r <= -360))
myRobot.print_position(); // back at origin
r = r - (double) floor(r/360)*360; }
if (r < 0) --> c++ -o robot.exe robot.cpp robotMain.cpp
r = r + 360; --> robot.exe
return; X: 0, Y: 0, R: 0
} X: 0, Y: 100, R: 0
void robot::print_position ()
{ X: 200, Y: 100, R: 90
cout << "X: " << x << ", Y: " << y << ", R: " << r << "\n"; X: 200, Y: 3.58979e-07, R: 0
return; X: 0, Y: -7.17959e-07, R: 270
} -->