为什么打印一个变量会改变它的值?

Why would printing a variable change its value?

本文关键字:改变 变量 一个 打印 为什么      更新时间:2023-10-16

我有一个小函数,它应该是基于机器学习算法进行预测。这个函数不工作,所以我放了一条print语句来检查值,突然它开始工作了。当我注释掉打印行时,它又停止工作了。这一切发生的原因,我是不是漏掉了什么?

int makePrediction( const InstanceT & instance, bool biased ){
  double dotProduct = ( biased ? instance * _weights + _bias : instance * _weights ); 
  std::cout << "dotProduct = " << dotProduct << std::endl;
  return ( dotProduct > 0 ? 1 : -1 );
}

由于某种原因产生了与

不同的结果
int makePrediction( const InstanceT & instance, bool biased ){
  double dotProduct = ( biased ? instance * _weights + _bias : instance * _weights ); 
  return ( dotProduct > 0 ? 1 : -1 );
}

和显示相同输入的结果是不同的,我用

调用这个函数:
std::vector<InstanceT> _instances = populate_data() //this works for both versions
for ( int i = 0; i < _instances.size(); i++ ){
  std::cout << "prediction: " << makePrediction( _instances[i], true ) << std::endl;
}

任何想法吗?

这种情况经常发生,原因有两个:

  1. 并发问题。如果你的程序是多线程的,你可以用调试输出掩盖竞争条件。试试像helgrind这样的MT调试器。
  2. 破碎的堆栈。试着在你的程序上运行valgrind,看看它是否干净。

当然,这些都是非常通用的建议,但你必须更好地说明你的问题,以获得更好的建议:-)。