c++ - 好奇除法结果

标签 c++

这段代码怎么...

vector<double> _pc;
vector<int> _documentClassIds;

[...]

someMemberFunction(vector<int> const & documentIds) {

  cout << "_pc[0] = "<< _pc[0]<<endl;
  cout << "_pc[1] = "<< _pc[1]<<endl;
  cout << "documentIds.size() = " << documentIds.size()<<endl;

  // Normalize
  for (auto documentId : documentIds)
    _pc[_documentClassIds[documentId]] =
    _pc[_documentClassIds[documentId]] / documentIds.size();
  cout << "_pc[0] = "<< _pc[0]<<endl;
  cout << "_pc[1] = "<< _pc[1]<<endl;
}

产生这个输出?

_pc[0] = 3
_pc[1] = 3
documentIds.size() = 6
_pc[0] = 0.0138889
_pc[1] = 0.0138889

最佳答案

我不确定您认为问题出在哪里。

您有六个 个文档 ID,因此您的 for 循环运行了六次。每次运行时,它都会将您的 _pc 数组值之一除以六。

因为 0.0138888... 是 3 除以 216 (6^3),计算似乎是正确的。

很明显,选择要划分的 _pc 数组条目是平均分配的,因此每个都被划分了 3 次,所以每个最终都是:

(((3 / 6) / 6) / 6) => 0.013888...

关于c++ - 好奇除法结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21272190/

相关文章:

c++ - 在 C++ 中,调用 delete 运算符时会发生什么?

c++ - cmake - 如何根据使用它的人为目标库定义符号

c++ - 二维数组中的自动初始化对象?

c++ - 如何使用 regex_replace?

c++ - 如何检测之前连接的 SSL/TCP 套接字上的互联网断开连接?

c++ - vector 不满足 Eigen 3.4 中的 std::ranges::contiguous_range

c++ - 如何正确构建相互引用的类? (C++)

C++字符串文字仍然令人困惑

c++ - 从文本文件中读取行和列 QT GUI C++

c++ - std::list 顺序有保证吗?