Ejercicio
Float, Unidades De Velocidad
Objectivo
Cree un programa en C# para pedirle al usuario una distancia (en metros) y el tiempo empleado (como tres números: horas, minutos, segundos), y muestre la velocidad, en metros por segundo, kilómetros por hora y millas por hora (pista: 1 milla = 1609 metros).
Ejemplo Ejercicio C#
Mostrar Código C#
using System; // Import the System namespace to use basic classes like Console
class Program // Define the main class of the program
{
static void Main() // The entry point of the program
{
// Ask the user for the distance in meters
Console.Write("Enter the distance in meters: "); // Display prompt for distance
float distance = float.Parse(Console.ReadLine()); // Read and parse the user's input for distance
// Ask the user for the time in hours, minutes, and seconds
Console.Write("Enter the time in hours: "); // Prompt for hours
int hours = int.Parse(Console.ReadLine()); // Read and parse the hours
Console.Write("Enter the time in minutes: "); // Prompt for minutes
int minutes = int.Parse(Console.ReadLine()); // Read and parse the minutes
Console.Write("Enter the time in seconds: "); // Prompt for seconds
int seconds = int.Parse(Console.ReadLine()); // Read and parse the seconds
// Calculate the total time in seconds
int totalTimeInSeconds = (hours * 3600) + (minutes * 60) + seconds; // Convert hours and minutes to seconds and add the seconds
// Calculate speed in meters per second
float speedInMetersPerSecond = distance / totalTimeInSeconds; // Speed = distance / time
// Calculate speed in kilometers per hour
float speedInKilometersPerHour = (distance / 1000) / (totalTimeInSeconds / 3600f); // Speed in km/h = (distance in meters / 1000) / (time in seconds / 3600)
// Calculate speed in miles per hour
float speedInMilesPerHour = (distance / 1609) / (totalTimeInSeconds / 3600f); // Speed in mph = (distance in meters / 1609) / (time in seconds / 3600)
// Display the calculated speeds
Console.WriteLine($"Speed in meters per second: {speedInMetersPerSecond:F2} m/s"); // Display speed in meters per second, formatted to 2 decimal places
Console.WriteLine($"Speed in kilometers per hour: {speedInKilometersPerHour:F2} km/h"); // Display speed in km/h, formatted to 2 decimal places
Console.WriteLine($"Speed in miles per hour: {speedInMilesPerHour:F2} mph"); // Display speed in mph, formatted to 2 decimal places
}
}
Salida
Enter the distance in meters: 1500
Enter the time in hours: 1
Enter the time in minutes: 30
Enter the time in seconds: 45
Speed in meters per second: 1.03 m/s
Speed in kilometers per hour: 3.71 km/h
Speed in miles per hour: 2.31 mph
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp