Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost.
Condition: Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result!
Here is my Program:
static void Main(String[] args)
{
double mealCost=Convert.ToDouble(Console.ReadLine());
int tipPercent=Convert.ToInt32(Console.ReadLine());
int taxPercent=Convert.ToInt32(Console.ReadLine());
double tip,tax;
tip=(mealCost*(tipPercent/100));
tax=(mealCost*(taxPercent/100));
double totalCost=mealCost+tip+tax;
Console.WriteLine("The total meal cost is {0} dollars",totalCost);
Console.ReadLine();
}
But I had the output as 12.
My Expected output is 15.
If my sample input is 12.00 20 8
My calculation as tip=2.4
and tax=0.96
, totalCost=15.36
and the rounded value is
(round)totalCost=15
.
But the output came as 12.
How do I get the correct output in C#. Can anyone provide me some suggestions to resolve this issue.
What you have to do is, take tipPercent
and taxPercent
as double values or else implicitly convert them to double before processing division like the following:
tip = (mealCost * ((double)tipPercent / 100));
tax = (mealCost * ((double)taxPercent / 100));
Then you will get totalCost=15.36
for the input specified in the question. Much smarter solution is :
double mealCost, tipPercent, taxPercent;
Console.WriteLine("Enter values for Meal Cost, Tip percentage and tax percentage");
if (!double.TryParse(Console.ReadLine(), out mealCost))
{
Console.WriteLine("Invalid input for meal Cost");
}
if (!double.TryParse(Console.ReadLine(), out tipPercent))
{
Console.WriteLine("Invalid input for Tip percentage");
}
if (!double.TryParse(Console.ReadLine(), out taxPercent))
{
Console.WriteLine("Invalid input for Tip tax Percent");
}
double tip = (mealCost * (tipPercent / 100));
double tax = (mealCost * (taxPercent / 100));
double totalCost = mealCost + tip + tax;
Console.WriteLine("The total meal cost is {0}", totalCost.ToString("C0"));
Console.ReadLine();