/***************************************************
Write a program that allows the user to enter a
sequence of "moves" and prints out their position
after the moves. Moves are:
left - means a 90 deg counter clockwise turn (in place)
right - means a 90 deg clockwise turn (in place)
step - means step forward 1 unit
stop - terminates the sequence of moves.
The initial position is (0,0) facing North (up).
So the sequence "left step step left step right stop"
would leave you at (-2,-1).
***************************************************/
**#include <iostream>**
**#include <string>**
**#include <cmath>**
**using** **namespace** std;
**int** main()
**{**
// Initialize
**double** PI;
PI = 3.14159265;
**int** x, y, angle;
x = y = 0;
angle = 90;
string next;
cout << "Enter moves: ";
cin >> next;
// Loop processing the "next" command at each iteration
**while**(next != "stop")
**{**
**if** (next == "left")
**{**
angle = angle + 90;
**}**
**else** **if** (next == "right")
**{**
angle = angle + 270; // Two wrongs don't equal a right, but three lefts do!
**}**
**else** **if** (next == "step")
**{**
x = x + floor(cos(angle*PI/180) + 0.5); // See note below.
y = y + floor(sin(angle*PI/180) + 0.5);
**}**
// Read next command
cin >> next;
**}**
// Print final position
cout << "Final position is "
<< '(' << x << ',' << y << ')' << endl;
**return** 0;
**}**
/* NOTE:
We can't just use sin(angle) and cos(angle). First of all the cmath
functions expect angles to be given in radians. Second of all, sin and
cos return doubles, which are decimal approximations of real numbers.
So sin might return 0.9998 rather than 1. When that is implicitly cast
to an int, everthing after the decimal point is truncated, so 0.9998
becomes 0 instead of 1. What we need to do is round to the nearest int.
Unfortunately, cmath has floor and cieling but not "round to nearest".
Turns out that that "floor(z + 0.5)" is the same as "round to nearest".
Think about it!
*/