C# Practice: Making a Tip Calculator
As we’re getting used to coding, its good to practice and take part in challenges. In this challenge, we’re going to go through how to make a script run some calculations for us. Here’s what we need:
- A variable representing the bill of $40.
- A variable representing the percentage of the tip. (The user has the option of adding what they want. Default would be 20%)
- A variable that represents the percent in the form of a decimal. (C# doesn’t know what a percent is, we have to tell it what it is.)
- A variable that represents how much the tip actually is.
- A variable that is the sum of the bill and the tip.
Only three steps, seems simple enough. Lets start with the bill. It’s a number, but since there is a chance the answer might have a decimal value, let’s assign it as a float.
Now what I think would be cool is if all the user had to do was type in the percentage as is, no need to convert it into a decimal value themselves.
Lets make the tip a float as well, then make another variable that will be the result when its converted into a decimal value. Don’t forget to make tip public, so the user has control to change the amount.
Now a percentage is parts of a whole, and in math that whole is 100. To turn the tip into a decimal, we’ll need to divide it by 100. This part of code will need to be placed in the Start function. After that, we take tipValue and multiply it with the bill, this will give us how much money the tip actually is.
Now just to add the tipTotal to the bill, make sure the console will display the answer, and we’ll get the end result!
Let’s see if it works!
Wonderful! Now let’s change some of the numbers in Unity itself and see if it still works! Let’s make the bill 123, and the tip 15.
Sweet! It looks like it was a good choice to use floats!
That’s it for this challenge, have fun coding!