5. Calculate with numbers
If ore is divided among several crates, how much is there altogether? Have your spell calculate it using int variables, which store whole numbers.
Arithmetic symbols
| Symbol | Operation | Example and result |
|---|---|---|
| + | Addition | 2 + 3 gives 5 |
| - | Subtraction | 8 - 3 gives 5 |
| * | Multiplication | 2 * 3 gives 6 |
| / | Division | 8 / 2 gives 4 |
Use an asterisk for multiplication and a slash for division. Multiplication and division take precedence, just as in ordinary arithmetic. Parentheses come first, so (2 + 3) * 4 gives twenty.
Integer division discards the fractional part. 5 / 2 gives two. You cannot divide by zero.
Store a result
public class Program : ArcaneProgram
{
public void OnStart()
{
int orePerCrate = 80;
int count = 3;
int total = orePerCrate * count;
Workshop.Log.Write("Calculation finished.");
}
}For practice, imagine three crates holding 80 ore each. orePerCrate is the amount in each crate, and count is the number of crates. This spell does not change your actual storage. Substitute the values into orePerCrate * count: eighty times three gives 240, which is assigned to total.
The log displays only Calculation finished. Write takes a string, so this example does not display the calculated number directly. The next chapter teaches how to check a value using a condition.
Update a value using its current value
count = count + 1; reads count on the right, adds one, then stores the result on the left. If count was three, it becomes four. Here, = means assignment rather than a mathematical equation.
Changing count does not automatically change total. Execute total = orePerCrate * count; again to recalculate using the current values.
Exercise
Change count from three to four after total has been calculated, then recalculate total.
- What is total before recalculation?
- What is it after recalculation?
Show example solutionHide example solution
The total changes from 240 to 320 when you recalculate it. total keeps the result previously assigned to it. Changing count does not automatically rewrite total.
After the declaration of total, add count = 4; followed by total = orePerCrate * count; to perform the update.
