|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/expressions.txt
Explainer on Expressions (for quiz 2)
You will be given a few problems that ask how C would evaluate the expressions.
If you look at the "C Operator Precedence Table" link under Links, You will see this
* / % : multiplication, division, modulus
+ - :addition, subtraction
Multiplication, division, and modulus have higher precedence than either addition or subtraction.
If you have two operations with the same precedence, you will evaluate them from left-to-right.
If you don't remember, modulus finds the remainder after dividing two numbers.
Also, you will need to keep in mind what data type the numbers are. If you don't
see a decimal point in a number, it defaults to an int, a data type that can
only handle whole numbers. If you do see a decimal point, it is considered a
float, a datatype that can handle decimals.
So in this case:
2 - would be considered an integer
2.0 - would be considered a float
When evaluating expressions, if you see a float anywhere in the expression, then
the answer will be a float. Otherwise, it will be an integer.
Let's look at some expressions
Start Here: 2 * 2 % 2
4 % 2 - We evaluate the multiplication first (as it's on the left)
0 - Then we evaluate the modulus to get the final result
Start Here: 5 + 5 / 10
5 + 0 - We evaluate the division first, as that has higher precedence.
Notice that we got 0. Since 5 and 10 do not have decimal
points, we treat them as integers, so when we divide, we
essentially divide as normal (to get 0.5), but drop everything
after the decimal point, which results in 0
5 - Then we just add.
Now consider the following two expressions
2 / 4 and 2 / 4.0
These two expressions, while nearly identical, will give you different answers.
In the first expression, both 2 and 4 are treated as integers, so the answer
will be an integer as well, which means that it has to be a whole number, and
thus cannot be a decimal.
So in this case 2 / 4 = 0
In the second expression, while 2 is an integer, 4.0 has a decimal point, which
means that 4.0 is a float. Since there is a float in the expression, our answer
will be a float as well, thus, we can have a decimal answer.
So, in this case 2 / 4.0 = 0.5
To recap:
* Multiplication, Division and modulus have higher precedence over addition and subtraction.
* Operators with the same precedence get evaluated from left to right.
* ints only deal with whole numbers, floats can handle decimals
* treat numbers without a decimal point as an int, and numbers with a decimal
point as a float
* Expressions will only have a decimal answer if there is a float somewhere in
the expression.
|