okay, i am trying to convert cost per gallon to $2.89 and have the total cost fo
ID: 3720508 • Letter: O
Question
okay, i am trying to convert cost per gallon to $2.89 and have the total cost for the trip to equal $.012 instead of .121234545, will someone please help?
//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
decimal miles, gasoline;
decimal milesPerGallon;
decimal tot_miles = 0.00m;
decimal gas_cost = 0.00m;
Console.WriteLine(" Mileage Calculator ");
{
Console.Write(" Enter number of miles for a trip: ");
miles = Convert.ToInt32(Console.ReadLine());
Console.Write(" Enter average cost of gasoline: ");
gas_cost = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the MPG for vehicle: ");
gasoline = Convert.ToInt32(Console.ReadLine());
milesPerGallon = (decimal)miles / (decimal)gasoline;
tot_miles += milesPerGallon;
calculateCost(gasoline, gas_cost, tot_miles);
Console.WriteLine();
}
}
static void calculateCost(decimal milesPerGallon, decimal gas_cost, decimal tot_miles)
{
decimal cost = (( tot_miles / milesPerGallon ) * (decimal)gas_cost).ToSring("C"));
Console.WriteLine(" Cost of the trip is: " + cost);
}
}
}
Explanation / Answer
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
decimal miles, gasoline;
decimal milesPerGallon;
decimal tot_miles = 0.00m;
decimal gas_cost = 0.00m;
Console.WriteLine(" Mileage Calculator ");
{
Console.Write(" Enter number of miles for a trip: ");
miles = Convert.ToInt32(Console.ReadLine());
Console.Write(" Enter average cost of gasoline: ");
gas_cost = Convert.ToInt32(Console.ReadLine());
Console.Write(" Enter the MPG for vehicle: ");
gasoline = Convert.ToInt32(Console.ReadLine());
milesPerGallon = (decimal)miles / (decimal)gasoline;
tot_miles += milesPerGallon;
calculateCost(gasoline, gas_cost, tot_miles);
Console.WriteLine();
}
}
static void calculateCost(decimal milesPerGallon, decimal gas_cost, decimal tot_miles)
{
decimal cost = ( tot_miles / milesPerGallon ) * (decimal)gas_cost;
// Math.ROund() rounds the value to 2 decimal places
Console.WriteLine(" Cost of the trip is: " + Math.Round(cost, 2));
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.