Exercise
Float, Speed Units
Objective
Write a C# program to ask the user for a distance (in meters) and the time taken (as three numbers: hours, minutes, seconds), and display the speed, in meters per second, kilometers per hour, and miles per hour (hint: 1 mile = 1609 meters).
Write Your C# Exercise
C# Exercise Example
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
}
}