问题描述
double a;
a=3669.0;
int b;
b=a;
我正在在b中得到3668,而不是3669
i am getting 3668 in b, instead of 3669
我要如何解决这个问题?
如果有3559.8像也我要像3559不是3560
How do i fix This problem?. And if have 3559.8 like that also i want like 3559 not 3560
推荐答案
我怀疑你不这样做的真正的有这个问题 - 我怀疑你真的有:
I suspect you don't actually have that problem - I suspect you've really got:
double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0
// Now cast
int b = (int) a;
// Now a is 3668
是什么让我说的是,虽然这是事实,许多十进制值的无法的被精确保存在浮动
或双
,即不持有这种幅度的整数。他们可以很容易在二进制浮点形式精确地psented重新$ P $。 (非常大的整数,不能总是正好再presented,但我们不是一个非常大的整数处理在这里。)
What makes me say that is that although it's true that many decimal values cannot be stored exactly in float
or double
, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)
我强烈怀疑你的双击
值的实际的略小于3669.0,但它是由什么诊断设备,您向您显示为3669.0 '再使用。到一个整数值转换刚刚进行截断,而不是舍入 - 因此问题
I strongly suspect that your double
value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.
假设你的双击
类型是IEEE-754 64位的,这是不到3669.0正是最大的价值
Assuming your double
type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly
3668.99999999999954525264911353588104248046875
所以,如果你使用的任何诊断方法,即该值将显示为3669.0,那么它很可能(有可能,我会说),这是发生了什么。
So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.
这篇关于如何转换的双用C为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!