C语言 如何在C中将double转换为int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7657326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Convert double to int in C?
提问by ratty
double a;
a = 3669.0;
int b;
b = a;
I am getting 3668 in b, instead of 3669.
我在 b 中得到 3668,而不是 3669。
How do I fix This problem? And if have 3559.8 like that also I want like 3559 not 3560.
我该如何解决这个问题?如果有这样的 3559.8,我也想要 3559 而不是 3560。
回答by Jon Skeet
I suspect you don't actuallyhave 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
What makes me say that is that although it's true that many decimal values cannotbe stored exactly in floator 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.)
是什么让我说的是,虽然这是事实,许多十进制值不能精确地存储在float或者double,这并不适用于这种大小的整数。它们可以很容易地以二进制浮点形式精确表示。(非常大的整数不能总是精确表示,但我们在这里不处理非常大的整数。)
I strongly suspect that your doublevalue is actuallyslightly 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.
我强烈怀疑您的double值实际上略小于 3669.0,但是您使用的任何诊断设备都会将其显示为 3669.0。转换为整数值只是执行截断,而不是舍入 - 因此存在问题。
Assuming your doubletype is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly
假设您的double类型是 IEEE-754 64 位类型,则小于 3669.0 的最大值正好是
3668.99999999999954525264911353588104248046875
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.
因此,如果您正在使用该值显示为 3669.0 的任何诊断方法,那么很可能(可能,我会说)这就是正在发生的事情。
回答by Jeegar Patel
main() {
double a;
a=3669.0;
int b;
b=a;
printf("b is %d",b);
}
output is :b is 3669
输出是:b is 3669
when you write b=a; then its automatically converted in int
当你写 b=a; 然后它自动转换为 int
see on-line compiler result :
回答by Shamim Hafiz
This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.
这就是臭名昭著的浮点舍入问题。只需添加一个非常小的数字即可纠正问题。
double a;
a=3669.0;
int b;
b=a+ 1e-9;
回答by Gouse Shaik
int b;
double a;
a=3669.0;
b=a;
printf("b=%d",b);
this code gives the output as b=3669 only you check it clearly.
此代码给出的输出为 b=3669,只有您清楚地检查它。

