计算期间的 C++ 奇怪值

标签 c++ math

我有以下行:

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/

相关文章:

ruby - 重新排列序列以最大化顺序差异,ruby

c++ - 如何制作文件名和设置扩展名

c++ - c++ sizeof 运算符如何计算大小?

使用算法将未绑定(bind)值转换为绑定(bind)值?

javascript - 为什么 Infinity/Infinity 不是 1?

python - 如何在 python 中以有理数形式打印/显示表达式

c++ - 如何正确抛出一个不仅仅需要构造函数的异常?

c++ - 访问和打印用 new 初始化的 vector 的 vector

c++ - 获取 char* 缓冲区中的第一个字节

c - C编程数字和山脉