开发者

Type of the quotient of two integers

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜