Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
因为增量之前的值并不正好是0.0。您没有向我们提供足够的信息来评估原因。可能是这样。
假设 IEEE-754 浮点算术(这是一个非常安全的假设),浮点加法(其中操作数和数学结果都可以精确地以浮点格式表示)会产生精确结果的表示。
如果您希望数组的元素始终具有整数值,那么您可能应该使用整数元素类型。如果您选择 double 作为其可表示值的范围,那么您可能会搬起石头砸自己的脚,因为相对于整数类型增加的范围是以有限的精度为代价的。如果您需要表示大于
unsigned long long int
可以表示的精确整数,那么您需要一个任意精度的数学库,例如 GMP。Because the value before the increment was not exactly 0.0. You have not given us enough information to evaluate why that might be.
Assuming IEEE-754 floating-point arithmetic (which is a pretty safe assumption), floating-point additions where the operands and the mathematical result are all exactly representable in the floating point format produce a representation of the exact result.
If you expect the elements of your array always to have integer values, then you probably should use an integer element type. If you chose
double
for its range of representable values then you may have shot yourself in the foot, because the increased range relative to integer types comes at the cost of limited precision. If you need to represent exact integers larger thanunsigned long long int
can represent then you need an arbitrary-precision math library such as GMP.