Since a computer does math for you, programming math is easy. All you have to know is which symbols to use.
The easiest form of math in programming takes this form :
result = number1 (operator) number2
An operator is the symbol that defines the mathematical operation, such as the plus sign.
Addition
The symbol (operator) for addition is the plus sign ( + ).
*English*
The total difficulty rating of two monsters.
*Code*
total_difficulty = monst_1_diff + monst_2_diff
The player has just killed a monster in an RPG.
*English*
Give the player 2 more experience points.
*Code*
experience = experience + 2;
This may look tricky at first. To help clarify, here are the steps that the computer takes to perform this calculation :
First, the experience variable on the right of the assignment operator is turned into the number it contains. We'll assume it contains the number 5.
experience = 5 + 2;
Then, it adds 5 to 2
experience = 7;
And finally, we are back to simply giving a variable a number to hold. This final step is just like one you learned in the last chapter.
Subtraction
The operator for subtraction is the minus sign ( - ).
The player has just been struck by a bullet.
*English*
Subtract 5 from the player's health.
*Code*
player_health = player_health - 5
Multiplication
The operator for multiplication is ( * ). This is found above the 8 on your keyboard.
*English*
The final score equals the amount of enemies hit multiplied by 100.
*Code*
final_score = enemies_hit * 100
Division
The operator for division is ( / ). This is found next to the right shift key on your standard keyboard.
*English*
Given a certain amount of experience points, each member of a 4-member
party will receive 1/4 of the total experience.
*Code*
party_member_exp = total_exp_points / 4