我有以下行:
int iEndFrame = ((uByteStart + uByteCount-1) / g_iByteSize1FrameDecoded) + 1;
我的值(value)观是:
uByteStart = 2147479808
uByteCount = 8684
g_iByteSize1FrameDecoded = 1920
然而,iEndFrame 变成-1118477,这不可能是正确的。
有人看到我的错误吗?
谢谢你的帮助!
附言: 声明是:
void CApp::pCalcFrames(int uByteStart, int uByteCount, int &uStartFrame, int &uFramesToRead, int& uOffset)
最佳答案
uByteStart + uByteCount
回绕到负值,因为它超过了您平台上的 int
的大小(假设为 32 位)。
重要的是不要这样做,因为从技术上讲,这种行为是未定义的,因此您的代码将不可移植:
(§5/5 C++03, §5/4 C++11) If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.
一个解决方案(但请注意,由于连续整数除法的截断效应,它不会那么精确)是写
uByteStart / g_iByteSize1FrameDecoded + (uByteCount-1) / g_iByteSize1FrameDecoded + 1;
这减少了求和参数的大小。
关于计算期间的 C++ 奇怪值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17542124/