Type Casting

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?
Last edited on
xswtnsour13x wrote:
[...] when int a = 5, b = 12 [...]
static_cast<double>(a) results in a 2.4
It does not:
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
It does not cast 5 to 2.4 - did you open that link? Casting 5 to a double is still 5, or 5.0, not 2.4 - maybe you misread the book?
Last edited on
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) )

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.
I don't see anywhere "static_cast<double>(a)", but I do see "b / static_cast<double>(a)"
My mistake is in the question. Fair enough. All I want to know now is how does the rest give the result that they do?
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
Oh! Ok! Thanks for explaining. I really appreciate it.
Topic archived. No new replies allowed.