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).
Example C# Exercise
Show C# Code
using System;
class Program
{
static void Main()
{
Console.Write("Enter the distance in meters: ");
float distance = float.Parse(Console.ReadLine());
Console.Write("Enter the time in hours: ");
int hours = int.Parse(Console.ReadLine());
Console.Write("Enter the time in minutes: ");
int minutes = int.Parse(Console.ReadLine());
Console.Write("Enter the time in seconds: ");
int seconds = int.Parse(Console.ReadLine());
int totalTimeInSeconds = (hours * 3600) + (minutes * 60) + seconds;
float speedInMetersPerSecond = distance / totalTimeInSeconds;
float speedInKilometersPerHour = (distance / 1000) / (totalTimeInSeconds / 3600f);
float speedInMilesPerHour = (distance / 1609) / (totalTimeInSeconds / 3600f);
Console.WriteLine($"Speed in meters per second: {speedInMetersPerSecond:F2} m/s");
Console.WriteLine($"Speed in kilometers per hour: {speedInKilometersPerHour:F2} km/h");
Console.WriteLine($"Speed in miles per hour: {speedInMilesPerHour:F2} mph");
}
}
Output
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