PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How to display result as a decimal

 October 17, 2022     c#, decimal, integer     No comments   

Issue

Here is the homework problem:

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.

Here is my code:

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);

Solution

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.



Answered By - Bruno Pfohl
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing