The code snippet for the the problem is given below with all the functions properly commented.
The code uses a do-while loop when the variable treasure = false, the control enters the loop and calculates the distance given by the formula. Now in nested if-else statements user input is evaluated and the coordinates are printed after every input. Finally if the distance is zero than the treasure is found.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
int main()
{
int x = 15, y = 15; // Explorer’s coordinates
int x1, y1; // Treasure’s coordinates
int counter = 0; //<-- added counter
char direction;
double distance;
bool treasure = false;
srand(time(0));
x1 = rand() % 30 + 1;
y1 = rand() % 30 + 1;
do
{
distance = sqrt(static_cast<double>((x - x1)*(x - x1) + (y - y1)*(y - y1)));
cout << "Enter enter a direction to travel" << endl;
cin >> direction;
if (direction == 'n' || direction == 'N')
y += 1;
else if (direction == 's' || direction == 'S')
y -= 1;
else if (direction == 'e' || direction == 'E')
x += 1;
else if (direction == 'w' || direction == 'W')
x -= 1;
cout << "Your coordinates are now: " << endl;
cout << "X-Coordinate: " << x << endl;
cout << "Y-Coordinate: " << y << endl;
cout << "You are " << distance << " coordinates away from the treasure" << endl;
counter++;//<-- steps count up
if (distance == 0)
{
treasure = true;
cout << "Treasure Found" << endl;
return 0;
}
} while (treasure == false);
}
Get Answers For Free
Most questions answered within 1 hours.