1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> #include <cmath> #include <iomanip> // Class to represent a spacecraft class Spacecraft { public: Spacecraft(const std::string& name, double x, double y) : name(name), x(x), y(y), distanceTraveled(0.0) {} // Method to launch the spacecraft void launch() { std::cout << name << " has launched into space!\n"; } // Method to travel to a new position void travel(double newX, double newY) { double distance = std::sqrt(std::pow(newX - x, 2) + std::pow(newY - y, 2)); x = newX; y = newY; distanceTraveled += distance; std::cout << name << " traveled to (" << std::fixed << std::setprecision(2) << x << ", " << y << "). Distance traveled: " << distance << " units.\n"; } // Method to land the spacecraft void land() { std::cout << name << " has landed at (" << std::fixed << std::setprecision(2) << x << ", " << y << "). Total distance traveled: " << distanceTraveled << " units.\n"; } private: std::string name; double x, y; // Current position double distanceTraveled; }; int main() { // Create a spacecraft Spacecraft spacecraft("Voyager", 0.0, 0.0); // Simulate the space exploration spacecraft.launch(); spacecraft.travel(100.0, 150.0); // Travel to a new position spacecraft.travel(-50.0, 200.0); // Travel to another position spacecraft.land(); return 0; } |
Explanation
- Spacecraft Class:
- Attributes:
name
: Name of the spacecraft.x
,y
: Current coordinates of the spacecraft.distanceTraveled
: Total distance traveled by the spacecraft.
- Methods:
launch()
: Prints a message indicating that the spacecraft has launched.travel(double newX, double newY)
: Updates the spacecraft’s position to the new coordinates, calculates the distance traveled from the current position to the new position, and updates the total distance traveled.land()
: Prints the final position and total distance traveled when the spacecraft lands.
- Attributes:
- Main Function:
- Spacecraft Creation: Creates an instance of the
Spacecraft
class. - Simulation Sequence:
- Launches the spacecraft.
- Simulates traveling to various coordinates.
- Lands the spacecraft and prints the final status.
- Spacecraft Creation: Creates an instance of the
Usage
- Space Exploration Simulation: The program provides a basic model of space exploration, simulating the launch, travel, and landing of a spacecraft.
- Distance Calculation: Computes the Euclidean distance between points to simulate travel.