在表达式中应用什么转换(双精度到整数)
what the conversion is applied in the expression (double to int)
有一个表达式(作为中位数计算的一部分):
auto iter1 = std::next(first, floor(size/2) - 1 );
double result = *iter1 + *(iter1 + 1)) / 2;
其中迭代器下的值的类型是 int。
预期结果例如:
1.5 = (1 + 2 ) / 2
然而,在值 1 和 2 的情况下,结果为 1,看起来像是隐式转换为 int
请解释一下,这里应用的是什么规则(或者我的误解?)
在您的第二个表达式 double result = *iter1 + *(iter1 + 1)) / 2;
中:根据运算符优先级,*(iter1 + 1)) / 2
的计算首先完成;由于 /
运算符的操作数都是整数,因此 sub-expression 将导致 integer division。然后将整数除法的结果添加到 *iter1
.
there is an expression (as a part of median calculation):
double result = *iter1 + *(iter1 + 1)) / 2;
因为右侧表达式的常见类型是 int
。没有conversion完成。至少有一个 double
会解决你的问题。 (另请注意我为适合您的示例而添加的括号)。
double result = (*iter1 + static_cast<double>(*(iter1 + 1))) / 2.0;
有一个表达式(作为中位数计算的一部分):
auto iter1 = std::next(first, floor(size/2) - 1 );
double result = *iter1 + *(iter1 + 1)) / 2;
其中迭代器下的值的类型是 int。
预期结果例如:
1.5 = (1 + 2 ) / 2
然而,在值 1 和 2 的情况下,结果为 1,看起来像是隐式转换为 int
请解释一下,这里应用的是什么规则(或者我的误解?)
在您的第二个表达式 double result = *iter1 + *(iter1 + 1)) / 2;
中:根据运算符优先级,*(iter1 + 1)) / 2
的计算首先完成;由于 /
运算符的操作数都是整数,因此 sub-expression 将导致 integer division。然后将整数除法的结果添加到 *iter1
.
there is an expression (as a part of median calculation):
double result = *iter1 + *(iter1 + 1)) / 2;
因为右侧表达式的常见类型是 int
。没有conversion完成。至少有一个 double
会解决你的问题。 (另请注意我为适合您的示例而添加的括号)。
double result = (*iter1 + static_cast<double>(*(iter1 + 1))) / 2.0;