Puzzle 2.3 conversion of other types
What is the output of this program?
# Include <stdio. h>
# Define PR (x) printf (# X "= % G/T", (double) (x ))
# Define NL putchar ('/N ')
# Define print1 (X1) Pr (X1); NL
# Define print2 (x1, x2) Pr (X1); print1 (X2)
Main ()
{
Double D = 3.2, X;
Int I = 2, Y;
X = (y = D/I) * 2; print2 (x, y); (2.3.1)
Y = (x = D/I) * 2; print2 (x, y); (2.3.2)
Y = D x = 2.5/d); print1 (y); (2.3.3)
X = D * (y = (INT) 2.9 + 1.1)/d); print2 (x, y); (2.3.4)
}
Output:
X = 2 y = 1 (2.3.1)
X = 1.6 y = 3 (2.3.2)
Y = 2 (2.3.3)
X = 0 y = 0 (2.3.4)
Confusing 2.3 conversion of other types
2.3.1
Initial Value: D = 3.2, I = 2 |
|
X = (y = D/I) * 2 (X = (y = 3.2/2) * 2) |
|
(X = (y = 1.6) * 2) |
3.2 is a double floating point number, and 2 is an int integer. In terms of data type, the former is higher than the latter. Therefore, their operator will be a double floating point number. |
(X = 1*2), at this time, y = 1 |
Y is an int integer, which is obtained by dropping the decimal part of 1.6. |
(X = 2) 2. x = 2 |
|
2.3.2
Initial Value: D = 3.2, I = 2 |
|
Y = (x = D/I) * 2 (Y = (x = 1.6) * 2) |
|
(Y = 1.6*2), x = 1.6 |
Because X is a double floating point number, the result of this value assignment operation will also be a double floating point number. |
(Y = 1, 3.2) |
1.6 is a double floating point number. |
3. At this time, y = 3 |
Y is an int integer, which is obtained by dropping the decimal part of 3.2. |
2.3.3
Initial Value: D = 3.2, I = 2 |
|
Y = D * (x = 2.5/D) (Y = D * (x = 2.5/D )) |
|
(Y = D * 2.5/D), at this time x = 2.5/d |
Because X is a double floating point number, the accuracy of 2.5/D is retained. |
(Y = 1, 2.5) |
|
2. At this time, y = 2 |
Y is an int integer, which is obtained by dropping the decimal part of 2.5. |
2.3.4
Initial Value: D = 3.2, I = 2 |
|
X = D * (y = (INT) 2.9 + 1.1)/D) |
|
(X = D * (y = (2 + 1.1)/D )) |
The type conversion operation has a higher priority than "+ ". |
(X = D * (y = 3.1/D )) (X = D * (y = a decimal number )) |
|
(X = D * 0), then y = 0 |
Y is equal to 0 regardless of the "one decimal number", because the "one decimal number" is a value between 0 and 1. |
0. x = 0 |
|
Mixed Use of types: So far, mixing floating point numbers and integers in the same expression can cause surprising results. We have seen enough examples. When performing arithmetic operations, it is best to avoid mixing different types of operands. If you have to do that, you should be careful to use the type conversion operator to explicitly convert the related operands.