Operators are special symbols that are used to represent simple computations like addition and multiplication. Most of the operators in C++ do exactly what you would expect them to do, because they are common mathematical symbols. For example, the operator for adding two integers is +.
Expressions can contain both variables names and integer values. In each case the name of the variable is replaced with its value before the computation is performed.
Addition, subtraction and multiplication all do what you expect, but you might be surprised by division. For example, compile the following program around observe the output.
Listing2.7.1.This program is supposed to print the fraction of the hour that has passed since midnight. Youβll notice that the result isnβt quite what you expect. Read on to find out why!
The first line of output is what we expected, but the second line is odd. The value of the variable minute is 59, and 59 divided by 60 is 0, not 0.98333. The reason for the discrepancy is that C++ is performing integer division.
When both of the operands are integers (operands are the things operators operate on), the result must also be an integer, and by definition integer division truncates the answer. Truncating a value means dropping the decimal portion, even in cases like this where the next integer is so close.
Again the result is truncated, but at least now the answer is approximately correct. In order to get an even more accurate answer, we could use a different type of variable, called floating-point, that is capable of storing fractional values.
Construct a code block that prints the total cost of your meal, including the 6.0% sales tax, after you purchase two orders of fries, three burgers, and a milkshake. Start by initializing the value of sales tax, then the prices of the food. Once you have initialized the variables, you can perform your calculations and save the result in the price variable. At the very end, you will print out the total price.