Consider the following:
int num = 5;
double total = num / 2;
Is it correct to say that 开发者_C百科the quotient of num / 2
is not a double
because you need to parse the int
to double
?
The technical answer is that the /
operator produces an int when given two ints. This computation is done independent of its assignment to a double
variable.
You actually do get a double value in the variable total
, but it is 2.0, not 2.5. The integer 2 is cast to 2.0 in the initialization.
Your options, if you want 2.5, are:
double total = num / 2.0;
double total = (double)num / 2;
In short, it is not a parsing issue, but rather one of C++ operator semantics. Hope that made sense.
精彩评论