运算符+= 产生零

发布于 2024-11-13 01:50:52 字数 712 浏览 2 评论 0原文

[编辑]问题解决了——有点。从来没有真正的问题。看来调试器在骗我。谢谢[/编辑]

我有一个奇怪的问题,到目前为止我一直无法解决。我有一个私有类成员

private:
float *_histVals;

,它在构造函数中初始化如下:

// allocate memory for the histogram bins
size_t hSize = binsPerChan*binsPerChan*binsPerChan;
this->_histVals = new float[ hSize ];
for (size_t i = 0; i < hSize; ++i)
    this->_histVals[i] = 0.0f;

稍后在程序中,我想按以下方式向某些数组元素添加一些内容:

this->_histVals[ hIndex ] += imgFrac;

这里,imgFrac是大小为1.0 * e-5的浮点值,当前是_histVals[ hIndex ] 元素的值为零。然而,调试器显示执行该行后该值仍然为零。

我怀疑浮点精度有问题,但是当我对本地浮点变量尝试相同的操作时,它工作得很好。所以肯定和数组本身有关系。但我不知道那可能是什么。我还检查了数组边界内的索引。

有什么建议可能导致问题吗? 谢谢

[edit]Problem solved - kind of. There never really was a problem. It seems that the debugger was lying to me. Thanks[/edit]

I have a wierd problem that I've been unable to resolve so far. I have a private class member

private:
float *_histVals;

which is initialized in the constructor as follows:

// allocate memory for the histogram bins
size_t hSize = binsPerChan*binsPerChan*binsPerChan;
this->_histVals = new float[ hSize ];
for (size_t i = 0; i < hSize; ++i)
    this->_histVals[i] = 0.0f;

later in the program I want to add something to certain array elements in the following way:

this->_histVals[ hIndex ] += imgFrac;

Here, imgFrac is float value of the magnitude 1.0*e-5 and the current value of the _histVals[ hIndex ] Element is zero. However the debugger shows that after the execution of this line the value is still zero.

I suspected a problem with floating point precision but when I try the same thing with a local float variable it works perfectly. So it must have something to do with the array itself. But I've no idea what that possibly could be. I've also checked the index which is within array bounds.

Any suggestions what could cause the problem?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

¢好甜 2024-11-20 01:50:52

使用 std::vector 除非您想要过上困难的生活,或者您正在了解人们在过去的糟糕日子里是如何生活的。

关于这对数组元素没有影响:

this->_histVals[ hIndex ] += imgFrac;

可能的原因:

  • 调试器对你撒谎。
  • imgFrac 为零

您是否尝试过将所有涉及到 std::cout 的值记录下来?另外,为了让自己相信这并不涉及任何魔法,请尝试将其分解为:

float newValue = this->_histVals[ hIndex ] + imgFrac;
this->_histVals[ hIndex ] = newValue;

并记录 newValue

Use std::vector<float> unless you want a difficult life or you're learning how people had to live in the bad old days.

Regarding this having no effect on the array element:

this->_histVals[ hIndex ] += imgFrac;

Possible causes:

  • The debugger is lying to you.
  • imgFrac is zero

Have you tried logging all the values involved to std::cout? Also to convince yourself there's no magic involved, try breaking it down into:

float newValue = this->_histVals[ hIndex ] + imgFrac;
this->_histVals[ hIndex ] = newValue;

And log the newValue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文