C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
/* Compute the price */
beforeTax = tirePrice * numTires;
netSales = beforeTax + (beforeTax * SALESTAX);
printf("%You spent $%.2f on your tires\n\n\n", netSales);
return 0;
}

Here is a sample run of the program:


Click here to view code image


How many tires did you purchase? 4
What was the cost per tire (enter in $XX.XX format)? $84.99
You spent $363.76 on your tires

Order of Operators


As mentioned earlier in this chapter, C doesn’t always compute math operations in the order you
expect. The following expression explains it in a nutshell:


Click here to view code image


ans = 5 + 2 * 3; /* Puts 11 in ans */

If you thought that C would store 21 in ans, you’re reading the expression from left to right.
However, C always computes multiplication before addition. It sounds crazy, but as long as you know
the rules, you’ll be okay. C is following the order of operators table. C first multiplies 2 and 3 to get
6, and then adds 5 to get 11.


Table 9.1 lists the complete order of operators. (The table includes several operators you have yet to
cover—don’t worry, you will learn their value throughout the book.) For each level, if your
expression has more than one operator from the same level, C resolves them using the associativity
direction listed. So if you do multiplication and division, C performs the operation that appears first
when reading left to right, and then moves on to the next operation. When it has completed a level, it
moves down to the next level. As you can see in the table, , /, and % appear before + and -.
Therefore, if C sees an expression with a combination of these operators, it evaluates
, /, and %
before computing + and -.

Free download pdf