Write a program that computes speed: Takes distance (in meters) and time (as three numbers: hours, minutes, seconds), computes speed, in meters per second, kilometres per hour and miles per hour (hint: 1 mile = 1609 meters). Prints results to Console.
int distanceInMeters, hours, minutes, seconds;
Console.WriteLine("Please type distance in meters: ");
distanceInMeters = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type time in hours: ");
hours = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type time in minutes: ");
minutes = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type time in seconds: ");
seconds = Convert.ToInt32(Console.ReadLine());
int metersSecond, kmH, milesH;
metersSecond = distanceInMeters / ((hours * 3600) (minutes * 60) seconds);
kmH = (distanceInMeters / 1000) / (hours (minutes / 60) (seconds / 3600));
milesH = (distanceInMeters / 1609) / (hours (minutes / 60) (seconds / 3600));
Console.WriteLine("Your speed in meters/seconds is: " metersSecond);
Console.WriteLine("Please speed in km/h is: " kmH);
Console.WriteLine("Please speed in miles/h is: " milesH);
CodePudding user response:
Just cast any of the variables, say distanceInMeters
to decimal and use decimal datatype for the output variables.
distanceInMeters = Decimal.Parse(Console.ReadLine());
Your output will automatically be in decimal format. You can round
the digits if you want a certain level of precision.
CodePudding user response:
All of your variables in the following computation:
metersSecond = distanceInMeters / ((hours * 3600) (minutes * 60) seconds);
are of type int (whole number). Therefore the decimal places will be cut of. You can fix this by doing:
metersSecond = 1.0 * distanceInMeters / ((hours * 3600.0) (minutes * 60.0) seconds)
also metersSecond
should be declared type double, float or decimal, those types support the decimal places you want.