30 Days of Code - Day 2: Operators
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. Round the result to the nearest integer.
Example
meal_cost = 100
tip_percent = 15
tax_percent = 8
A tip of 15% * 100 = 15, and the taxes are 8% * 100 = 8. Print the value 123 and return from the function.
Solution in PHP:
We have a PHP script that is intended to calculate the total cost of a meal, including tax and tip, based on the meal cost, tip percentage, and tax percentage provided as input. You need to complete the solve
function to calculate the total cost and then call the solve
function with the provided input values. Here's how you can complete the solve
function:
<?php
/*
* Complete the 'solve' function below.
*
* The function accepts following parameters:
* 1. DOUBLE meal_cost
* 2. INTEGER tip_percent
* 3. INTEGER tax_percent
*/function solve($meal_cost, $tip_percent, $tax_percent) {
// Write your code here
$tip = $meal_cost * ($tip_percent / 100);
$tax = $meal_cost * ($tax_percent / 100);// Calculate the total cost
$total_cost = $meal_cost + $tip + $tax;// Round the total cost to the nearest integer
$total_cost = round($total_cost);// Print the total cost
echo $total_cost;
}$meal_cost = doubleval(trim(fgets(STDIN)));
$tip_percent = intval(trim(fgets(STDIN)));
$tax_percent = intval(trim(fgets(STDIN)));solve($meal_cost, $tip_percent, $tax_percent);
In this code, we first calculate the tip amount by multiplying the meal cost by the tip percentage divided by 100. Similarly, we calculate the tax amount using the tax percentage. Then, we add these amounts to the meal cost to get the total cost. Finally, we round the total cost to the nearest integer using the round
function and print it.