Punto 3D Ejercicio C# - Curso de Programación C# (C Sharp)

 Ejercicio

Punto 3D

 Objetivo

Cree una clase "Point3D", para representar un punto en el espacio 3D, con coordenadas X, Y y Z. Debe contener los siguientes métodos:

MoveTo, que cambiará las coordenadas en las que se encuentra el punto.
DistanceTo(Point3D p2), para calcular la distancia a otro punto.
ToString, que devolverá una cadena similar a "(2,-7,0)"
Y, por supuesto, getters y setters.

El programa de prueba debe crear una matriz de 5 puntos, obtener datos para ellos y calcular (y mostrar) la distancia desde el primer punto hasta los cuatro restantes.

 Código de Ejemplo

// Importing the System namespace to handle basic functionalities and console output
using System;

// Creating the class to represent a point in 3D space
public class Point3D
{
    // Declaring the coordinates of the point (X, Y, Z) in 3D space
    private double x;
    private double y;
    private double z;

    // Constructor to initialize the point with given coordinates (X, Y, Z)
    public Point3D(double x, double y, double z)
    {
        this.x = x;  // Setting the X coordinate
        this.y = y;  // Setting the Y coordinate
        this.z = z;  // Setting the Z coordinate
    }

    // Getter for the X coordinate
    public double X
    {
        get { return x; }  // Returning the X coordinate value
        set { x = value; } // Setting the X coordinate value
    }

    // Getter for the Y coordinate
    public double Y
    {
        get { return y; }  // Returning the Y coordinate value
        set { y = value; } // Setting the Y coordinate value
    }

    // Getter for the Z coordinate
    public double Z
    {
        get { return z; }  // Returning the Z coordinate value
        set { z = value; } // Setting the Z coordinate value
    }

    // Method to move the point to a new location by changing its coordinates
    public void MoveTo(double newX, double newY, double newZ)
    {
        x = newX;  // Updating the X coordinate to the new value
        y = newY;  // Updating the Y coordinate to the new value
        z = newZ;  // Updating the Z coordinate to the new value
    }

    // Method to calculate the distance from this point to another point
    public double DistanceTo(Point3D p2)
    {
        // Calculating the difference in the X coordinates between this point and the other point
        double dx = x - p2.X;
        // Calculating the difference in the Y coordinates between this point and the other point
        double dy = y - p2.Y;
        // Calculating the difference in the Z coordinates between this point and the other point
        double dz = z - p2.Z;

        // Using the 3D distance formula to calculate the distance between the two points
        return Math.Sqrt(dx * dx + dy * dy + dz * dz); // Returning the calculated distance
    }

    // Method to return a string representation of the point in the format (X, Y, Z)
    public override string ToString()
    {
        return $"({x},{y},{z})";  // Returning the string with the X, Y, Z coordinates in parentheses
    }
}

// Auxiliary class containing the Main method to test the functionality of the Point3D class
public class Program
{
    public static void Main()
    {
        // Creating an array of 5 Point3D objects to store the points
        Point3D[] points = new Point3D[5];

        // Loop to gather input for each point from the user
        for (int i = 0; i < 5; i++)
        {
            // Asking the user to input the coordinates for the current point
            Console.WriteLine($"Enter the coordinates for Point {i + 1}:");

            // Asking for the X coordinate and storing the input as a double
            Console.Write("X: ");
            double x = Convert.ToDouble(Console.ReadLine());

            // Asking for the Y coordinate and storing the input as a double
            Console.Write("Y: ");
            double y = Convert.ToDouble(Console.ReadLine());

            // Asking for the Z coordinate and storing the input as a double
            Console.Write("Z: ");
            double z = Convert.ToDouble(Console.ReadLine());

            // Creating a new Point3D object with the entered coordinates and storing it in the array
            points[i] = new Point3D(x, y, z);
        }

        // Storing the first point from the array to calculate distances from it
        Point3D firstPoint = points[0];

        // Displaying a message about the distances
        Console.WriteLine("\nDistances from the first point to the others:");

        // Loop to calculate and display the distance from the first point to the remaining points
        for (int i = 1; i < points.Length; i++)
        {
            // Calling the DistanceTo method to calculate the distance from the first point to the current point
            double distance = firstPoint.DistanceTo(points[i]);

            // Displaying the calculated distance from the first point to the current point
            Console.WriteLine($"Distance from Point 1 to Point {i + 1}: {distance:F2} units");
        }
    }
}

Más ejercicios C# Sharp de POO Más sobre Clases

 Matriz de objetos: tabla
Cree una clase denominada "Table". Debe tener un constructor, indicando el ancho y alto de la placa. Tendrá un método "ShowData" que escribirá en la p...
 House
Cree una clase "House", con un atributo "area", un constructor que establezca su valor y un método "ShowData" para mostrar "Soy una casa, mi área es d...
 Tabla + coffetable + array
Cree un proyecto denominado "Tablas2", basado en el proyecto "Tablas". En él, cree una clase "CoffeeTable" que herede de "Table". Su método "ShowDa...
 Encriptador
Cree una clase "Encrypter" para cifrar y descifrar texto. Tendrá un método "Encrypt", que recibirá una cadena y devolverá otra cadena. Será un méto...
 Números complejos
Un número complejo tiene dos partes: la parte real y la parte imaginaria. En un número como a+bi (2-3i, por ejemplo) la parte real sería "a" (2) y la ...
 tabla + coffetable + leg
Amplíe el ejemplo de las tablas y las mesas de centro, para agregar una clase "Leg" con un método "ShowData", que escribirá "I am a leg" y luego mostr...
 Catálogo
Cree el diagrama de clases y, a continuación, con Visual Studio, un proyecto y las clases correspondientes para una utilidad de catálogo: Podrá alm...
 Número aleatorio
Cree una clase RandomNumber, con tres métodos estáticos: - GetFloat devolverá un número entre 0 y 1 utilizando el siguiente algoritmo: semilla =...
 Texto a HTML
Crear una clase "TextToHTML", que debe ser capaz de convertir varios textos introducidos por el usuario en una secuencia HTML, como esta: Hola Soy...
 Clase ScreenText
Cree una clase ScreenText, para mostrar un texto determinado en coordenadas de pantalla especificadas. Debe tener un constructor que recibirá X, Y y l...
 Clase ComplexNumber mejorada
Mejore la clase "ComplexNumber", para que sobrecargue los operadores + y - para sumar y restar números....
 Catálogo + Menú
Mejorar el programa Catálogo, de forma que "Principal" muestre un menú que permita introducir nuevos datos de cualquier tipo, así como visualizar todo...

Juan A. Ripoll - Tutoriales y Cursos de Programacion© 2025 Todos los derechos reservados.  Condiciones legales.