|
| 1 | +# 0026 Calculate Tip ( L-B ) |
| 2 | + |
| 3 | +## Problem |
| 4 | + |
| 5 | +You are at a restaurant, and you want to calculate the tip for your meal. Write a JavaScript function called **calculateTip** that takes two inputs: the total cost of the meal and the tip percentage.Your function should calculate the tip amount and return it. |
| 6 | + |
| 7 | +**Example** |
| 8 | + |
| 9 | +``` |
| 10 | +If the total cost is $50 and the tip percentage is 15%, the function should return $7.5 because 15% of $50 is $7.5. |
| 11 | +
|
| 12 | +If the total cost is $75 and the tip percentage is 20%, the function should return $15 because 20% of $75 is $15. |
| 13 | +``` |
| 14 | + |
| 15 | +- **_You can assume that the tip percentage is provided as a whole number (e.g., 15 for 15%) and that the total cost is a positive number._** |
| 16 | + |
| 17 | +**Here's an example of how the function should work:** |
| 18 | + |
| 19 | +```javascript |
| 20 | +console.log(calculateTip(50, 15)); // 7.5 |
| 21 | +console.log(calculateTip(75, 20)); // 15 |
| 22 | +``` |
| 23 | + |
| 24 | +## Solutions |
| 25 | + |
| 26 | +```javascript |
| 27 | +function calculateTip(totalCost, tipPercentage) { |
| 28 | + // Calculate the tip amount by multiplying totalCost by tipPercentage divided by 100 |
| 29 | + const tipAmount = (totalCost * tipPercentage) / 100; |
| 30 | + return tipAmount; |
| 31 | +} |
| 32 | + |
| 33 | +// Test cases |
| 34 | +console.log(calculateTip(50, 15)); // 7.5 |
| 35 | +console.log(calculateTip(75, 20)); // 15 |
| 36 | +``` |
| 37 | + |
| 38 | +## How it works |
| 39 | + |
| 40 | +1. We define a function calculateTip that takes two parameters: totalCost (the total cost of the meal) and tipPercentage (the percentage of the tip to be calculated). |
| 41 | + |
| 42 | +2. Inside the function, we calculate the tip amount by multiplying totalCost by tipPercentage divided by 100. This is because tip percentages are usually provided as whole numbers (e.g., 15 for 15%). |
| 43 | + |
| 44 | +## References |
| 45 | + |
| 46 | +- [ChatGPT](https://chat.openai.com/) |
| 47 | + |
| 48 | +## Problem Added By |
| 49 | + |
| 50 | +- [Tipchan](https://github.com/tsongtheng) |
| 51 | + |
| 52 | +## Contributing |
| 53 | + |
| 54 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
| 55 | + |
| 56 | +Please make sure to update tests as appropriate. |
0 commit comments