g*********s 发帖数: 1782 | 1 double x = ***;
int y = (int) x;
这里不是四舍五入。谁知道算法是什么?复杂度多少?
另外int转double的算法呢? |
s***e 发帖数: 122 | 2 你这个问题问得复杂了。我越想越觉得得去问搞汇编的同学们了。
【在 g*********s 的大作中提到】 : double x = ***; : int y = (int) x; : 这里不是四舍五入。谁知道算法是什么?复杂度多少? : 另外int转double的算法呢?
|
X****r 发帖数: 3557 | 3 什么语言?
如果是C/C++的话,规定是truncate,就是小数点后部分去掉。
【在 g*********s 的大作中提到】 : double x = ***; : int y = (int) x; : 这里不是四舍五入。谁知道算法是什么?复杂度多少? : 另外int转double的算法呢?
|
w***g 发帖数: 5958 | 4 是truncate。我记错了。一直当四舍五入用的,程序里不知道出了多少bug。
【在 X****r 的大作中提到】 : 什么语言? : 如果是C/C++的话,规定是truncate,就是小数点后部分去掉。
|
g*********s 发帖数: 1782 | 5 出现了这样的情况:double = 28032400.000000,int = 28032399。怎么回事呢?
【在 X****r 的大作中提到】 : 什么语言? : 如果是C/C++的话,规定是truncate,就是小数点后部分去掉。
|
X****r 发帖数: 3557 | 6 因为28032400.000000本身并不是这个浮点数的正真的值(即使你把这个常数赋给浮点
变量)。浮点数的精度是有限的。正如一个整型变量不能精确地表述1.5一样,浮点变
量只能精确表述有限个特定的有理数,而不是任意有理数。这个浮点变量实际的值比
28032400.000000略小一点点,所以转换成整数就成了28032399了。
因此,千万不要假定以浮点类型存储的整数转换成整型后还是原来整数的值。
【在 g*********s 的大作中提到】 : 出现了这样的情况:double = 28032400.000000,int = 28032399。怎么回事呢?
|
l***8 发帖数: 149 | 7 The "double" type has enough bits to hold small integers (such as 28032400)
without loss of accuracy. Here the "without loss of accuracy" means at the
magnitude of 1e+7 the error is less than +/- 0.5. Internally this number
might be 28032399.999 but after truncation you get 28032399.
Use round() to 四舍五入 |
x****u 发帖数: 44466 | 8 显然小的很啊,你搜搜汇编语言里面说的浮点数的含义,就明白了。
【在 g*********s 的大作中提到】 : double x = ***; : int y = (int) x; : 这里不是四舍五入。谁知道算法是什么?复杂度多少? : 另外int转double的算法呢?
|
O******e 发帖数: 734 | 9 Single-precision floating point number have 23 normalized bits of
accuracy in the mantissa, which gives six decimal places of accuracy,
and can represent integers up to 16777216 exactly.
Double-precision floating point numbers have 52 normalized bits of
accuracy in the mantissa, which gives 15 decimal places of accuracy,
and can represent integers up to 9007199254740992 exactly.
What is happening in your case is that you are starting with the single-
precision representation of 28032400.0, which
【在 g*********s 的大作中提到】 : 出现了这样的情况:double = 28032400.000000,int = 28032399。怎么回事呢?
|
z******i 发帖数: 59 | 10 It is a truncation. You can write a simple C code, and check its
assemly to figure out what it is doing. X86 has the fistpl (convert float to
integer) instruction to do that.
But be careful if performance is important in your code. Since the
conversion
is very slow (stall FPU due to fldcw - load FPU control word).
146 80483ee: d9 6d e4 fldcw -0x1c(%ebp)
147 80483f1: db 5d f4 fistpl -0xc(%ebp)
148 80483f4: d9 6d e6 fldcw -0x1a(%ebp)
int to
【在 g*********s 的大作中提到】 : double x = ***; : int y = (int) x; : 这里不是四舍五入。谁知道算法是什么?复杂度多少? : 另外int转double的算法呢?
|