Ejercicio
Área Perimetral
Objectivo
Crear un programa en C# para calcular el perímetro, el área y la diagonal de un rectángulo a partir de su anchura y altura (perímetro = suma de los cuatro lados, área = base x altura, diagonal utilizando el teorema de Pitágoras). Debe repetirse hasta que el usuario introduzca 0 para el ancho.
Ejemplo Ejercicio C#
Mostrar Código C#
using System; // Import the System namespace to use basic classes like Console and Math
class Program // Define the main class of the program
{
static void Main() // The entry point of the program
{
// Infinite loop to keep asking the user for input until they enter 0 for the width
while (true)
{
// Ask the user for the width of the rectangle
Console.Write("Enter the width of the rectangle (0 to quit): ");
double width = double.Parse(Console.ReadLine()); // Read the user's input and convert it to a double
// If the width is 0, exit the loop and end the program
if (width == 0)
{
Console.WriteLine("Goodbye!");
break; // Exit the while loop and end the program
}
// Ask the user for the height of the rectangle
Console.Write("Enter the height of the rectangle: ");
double height = double.Parse(Console.ReadLine()); // Read the user's input and convert it to a double
// Calculate the perimeter of the rectangle (sum of all sides)
double perimeter = 2 * (width + height);
// Calculate the area of the rectangle (base x height)
double area = width * height;
// Calculate the diagonal using the Pythagorean theorem (sqrt(width^2 + height^2))
double diagonal = Math.Sqrt(Math.Pow(width, 2) + Math.Pow(height, 2));
// Display the results
Console.WriteLine($"Perimeter: {perimeter}");
Console.WriteLine($"Area: {area}");
Console.WriteLine($"Diagonal: {diagonal}\n");
}
}
}
Salida
Enter the width of the rectangle (0 to quit): 5
Enter the height of the rectangle: 10
Perimeter: 30
Area: 50
Diagonal: 11.180339887498949
Case 2:
Enter the width of the rectangle (0 to quit): 7
Enter the height of the rectangle: 3
Perimeter: 20
Area: 21
Diagonal: 7.615779381305537
Case 3:
Enter the width of the rectangle (0 to quit): 0
Goodbye!
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp