Group
C# Basic Data Types Overview
Objective
1. Prompt the user to enter a distance in meters.
2. Ask the user to enter the time taken as three separate inputs: hours, minutes, and seconds.
3. Convert the total time into seconds.
4. Compute the speed in meters per second, kilometers per hour, and miles per hour.
5. Display the results in a clear and formatted manner.
6. Ensure proper input validation to handle incorrect or non-numeric values.
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()
{
// Ask the user to enter the distance in meters
Console.Write("Enter the distance (in meters): ");
double distance = Convert.ToDouble(Console.ReadLine());
// Ask the user to enter the time taken in hours, minutes, and seconds
Console.Write("Enter time - Hours: ");
int hours = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter time - Minutes: ");
int minutes = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter time - Seconds: ");
int seconds = Convert.ToInt32(Console.ReadLine());
// Convert the total time into seconds
double totalTimeInSeconds = (hours * 3600) + (minutes * 60) + seconds;
// Calculate speed in different units
double speedMetersPerSecond = distance / totalTimeInSeconds;
double speedKilometersPerHour = (distance / 1000) / (totalTimeInSeconds / 3600);
double speedMilesPerHour = (distance / 1609) / (totalTimeInSeconds / 3600);
// Display the results
Console.WriteLine("\nSpeed Calculations:");
Console.WriteLine($"Speed in meters per second: {speedMetersPerSecond:F2} m/s");
Console.WriteLine($"Speed in kilometers per hour: {speedKilometersPerHour:F2} km/h");
Console.WriteLine($"Speed in miles per hour: {speedMilesPerHour:F2} mph");
}
}
Output
Enter the distance (in meters): 500
Enter time - Hours: 0
Enter time - Minutes: 5
Enter time - Seconds: 0
Speed Calculations:
Speed in meters per second: 1.67 m/s
Speed in kilometers per hour: 6.00 km/h
Speed in miles per hour: 3.73 mph