I've been reading through the first chapters of my C++ text book and I don't understand Type Casting. In one of chapter 3's checkpoints, I am to give the results to questions such as
static_cast<double>(b / a) which result in a 2.0 while the problem static_cast<double>(b) / a
results in a 2.4 when int a = 5, b = 12?
static_cast<double>(a) results in a 2.4
also. How does that even happen? I understand that type casting converts the declared variable into another data type. I just don't understand why the results are what they are. Can someone please further explain to me?
It does not what? The checkpoints in my book have its answers at the back and for static_cast<double>(a), the answer listed is 2.4.
Please give an explanation as to why. Thanks
3.11
int a = 5, b = 12
double x = 3.4, z = 9.1;
A) b/a
B) x * a
C) static_cast<double>(b / a)
D) static_cast<double>(b) / a
E) b / static_cast<double>(a)
F) static_cast<double(b) / static_cast<double>(a)
G) b / static_cast<int>(x)
H) static_cast<int>(x) * static_cast<int>(z)
I) static_cast<int>(x * z)
J) static_cast<double>static_cast<int>(x) *
static_cast<int>(z) )
Answers
3.11 A) 2
B) 17.0
C) 2.0
D) 2.4
E) 2.4
F) 2.4
G) 4
H) 27
I) 30
J) 27.0
____________________________________________
Answers were copied from the book's PDF and I double checked the questions as I was typing them. Please explain why the answers are what they are. Thank you.
A: integer division
B: because x is a double, a gets implicitly upcasted/promoted to a double
C: the integer division happens before the cast to double
D: like with B, the double cast of b promotes a for the calculation as well
E: like with B and D, b gets promoted
F: just regular double division
G: x gets truncated to 3 and since b is also an int, you get integer division
H: x and z both get truncated to integers, then it's just multiplication
I: the truncating cast to int happens after the doubles have been multiplied, resulting in a more precise result
J: same as H, but cated to a double afterward so you get a .0 at the end of the number