|
|
|
|
|
|
|
Now the addition, left to right, is 5 + 3 = 8; 8 + 72 = 80; 80 + 24 = 104. |
|
|
|
|
|
|
|
|
Be careful with this. Some operators, such as assignment, are evaluated in right-to-left order! In any case, what if the precedence order doesn't meet your needs? Consider the expression |
|
|
|
|
|
|
|
|
TotalSeconds = NumMinutesToThink + NumMinutesToType * 60 |
|
|
|
|
|
|
|
|
In this expression you do not want to multiply the NumMinutesToType variable by 60 and then add it to NumMinutesToThink. You want to add the two variables to get the total number of minutes, and then you want to multiply that number by 60 to get the total seconds. |
|
|
|
|
|
|
|
|
In this case you use parentheses to change the precedence order. Items in parentheses are evaluated at a higher precedence than any of the mathematical operators. Thus |
|
|
|
|
|
|
|
|
TotalSeconds = (NumMinutesToThink + NumMinutesToType) * 60 |
|
|
|
|
|
|
|
|
will accomplish what you want. |
|
|
|
|
|
|
|
|
For complex expressions you might need to nest parentheses one within another. For example, you might need to compute the total seconds and then compute the total number of people who are involved before multiplying seconds times people: |
|
|
|
|
|
|
|
|
TotalPersonSeconds = ( ( (NumMinutesToThink + NumMinutesToType) * 60)
* (PeopleInTheOffice + PeopleOnVacation) ) |
|
|
|
|
|
|
|
|
This complicated expression is read from the inside out. First, NumMinutesToThink is added to NumMinutesToType, because these are in the innermost parentheses. Then this sum is multiplied by 60. Next, PeopleInTheOffice is added to PeopleOnVacation. Finally, the total number of people found is multiplied by the total number of seconds. |
|
|
|
|
|
|
|
|
This example raises an important issue. This expression is easy for a computer to understand, but very difficult for a human to read, understand, or modify. Here is the same expression rewritten, using some temporary integer variables: |
|
|
|
|
|
|
|
|
TotalMinutes = NumMinutesToThink + NumMinutesToType;
TotalSeconds = TotalMinutes * 60;
TotalPeople = PeopleInTheOffice + PeopleOnVacation;
TotalPersonSeconds = TotalPeople * TotalSeconds; |
|
|
|
|
|
|
|
|
This example takes longer to write and uses more temporary variables than the preceding example, but it is far easier to understand. Add a comment at the top to explain what this code does, and change the 60 to a symbolic constant. You then will have code that is easy to understand and maintain. |
|
|
|
|
|