Let’s attempt to put to use some of our knowledge on data structures to something useful! Let’s write a program that calculates the percentage of health that a player has remaining (we can then use this information for something else, like updating a display on the user’s screen).
Start a new console project in Visual Studio, choose a name you like, and then enter the following code blocks inside the brackets of static void Main(string[] args) (the Main function, and entry-point for this application).
The Setup
First, let’s go ahead and define an integer value to contain both the player’s total and current HP (since, fractional health isn’t typically utilized):
// Player's Total HP int total_HP = 220; // Player's Current HP int current_HP = 15;
Now that we have a variable for both the player’s total and current health, we can now calculate the percentage of health the player has remaining by using the following:
// Calculates the % of health remaining int percent_Health_Remaining = (current_HP / total_HP) * 100;
Simple enough! We could have stored the percentage in a double, but let’s just say for argument’s sake that we don’t care about the fractional percentage component (6% vs. 6.21%). Now, just to verify that our calculation has been performed to our expectation–let’s print the value to the console via:
// Prints the percentage of the player health to the screen
Console.WriteLine("Percent of health remaining: " + percent_Health_Remaining);
// Waits for user input before closing the console
Console.ReadLine();
Now, run your program by pressing F5 or by going to Debug -> Start Debugging. What value did it print? If we perform a hand calculation based on the numbers provided, we should get 6.82%. But why did it print 0?
In order to understand what’s going on, let’s walk through the calculation as the computer does: The first thing it will do is divide the current_HP value by the total_HP value. By hand this gives us 0.0682–however, integers can not store fractional components. At this point the result of the division becomes 0 as the decimal component is truncated. Multiplying 0 by 100 still gives us the result that we didn’t expect: 0.
How do we fix this?
As in most cases, there are a lot of ways to fix this. We could change all the values to double! That would solve the problem as all the fractional components would carry over to the final equation. But what if we wanted to keep everything as an integer?
One way to solve this problem without changing data types is to perform what is called as an explicit cast. An explicit cast is a way to tell your program to treat a value as a different data type. For the purposes of the calculation that we are trying to achieve, we could change the percent_Health_Remaining calculation to:
int percent_Health_Remaining = (double)current_HP / (double)total_HP * 100;
Now, as you look at this line, Visual Studio will actually underline it and report the following error:
Cannot implicity convert type ‘double’ to ‘int’. An explicit conversion exists (are you missing a cast?)
The result of the right hand side of the equal sign is now a double, and Visual Studio is correctly complaining that you can’t implicitly cast from a double to an int. After all, we are still trying to force a double into an integer which results in a loss of data (due to truncation of the decimal component). To fix this, encompass the entire right hand side with parentheses and explicitly cast the result of the expression into an integer:
int percent_Health_Remaining = (int)((double)current_HP / (double)total_HP * 100);
Re-run your program, and you should see now that we are achieving the expected result of 6%. Remember that when explicitly casting from a double to an integer that the fractional component is simply chopped off (no rounding occurs). This is why the result is 6%, and not 7% as you might expect (we’ll cover a way around this later).
