c++ - 在表达式中应用什么转换( double 到整数)

标签 c++ implicit-conversion

有一个表达式(作为中位数计算的一部分):

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 先完成;由于 / 运算符的操作数都是整数,因此子表达式将导致 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;

关于c++ - 在表达式中应用什么转换( double 到整数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41881626/

相关文章:

c++ - 为什么这个 Github 项目将字符串转换为 bool 值?

c++ - -fsanitize=address 使用 clang++ 与 g++ 的不同输出

c++ - 使用 boost.spirit 时不推荐使用的警告

c++ - 使用 boost::variant C++ 的隐式运算符重载

implicit-conversion - pybind11 implicitly_convertible 不起作用

scala - Akka-Http DSL 发生了什么?

c++ - 什么是双关语,它的目的是什么?

c++ - strcpy c++ 无法从字符串 char* 转换参数 1

c++ - 是否有一个 Visual Studio 插件可以防止编写不匹配的 { 和 }

c++ - `decltype(&ordenary_func)`和decltype`(ordenary_func)之间的区别