好的,我有一个简单的问题。在我的冒险中,我寻求数据类型中可以容纳的最大数字,并且我正在尝试诸如 long int 、 doubles 和 float 等。
但是在最简单的赋值中,例如 Float x = 12345789 ,它给我 123456792 作为输出。 这是代码
#include <stdio.h>
int main()
{
int x = 1234567891 ;
long int y = 9034567891234567899;
long long int z = 9034567891234567891;
float t = 123456789 ;
printf("%i \n%li \n%lli \n%f \n ",x,y,z,t);
}
我得到的输出是
1234567891
9034567891234567899
9034567891234567891
123456792.000000
我在 Linux 上使用 gcc 进行编码。可能是什么问题?
为了清楚起见,如果您给出更高的数字,例如
float t = 123456789123456789
它将得到前 9 个正确的数字,但会在不应该得到的地方对最后的数字进行某种舍入。
1234567890519087104.000000
如果我的工作超出 0(如 0.00123),我可以理解它,但它只是直接使用整数来找出 float 的限制。
最佳答案
- 作为一名视觉和体验式学习者,我建议您借助 https://www.h-schmidt.net/FloatConverter/IEEE754.html 等在线转换器,仔细了解 float 在位世界中的表示方式
Value: 123456789
Hexadecimal representation: 0x4ceb79a3
Binary representation: 01001100111010110111100110100011
sign (0) : +1
exponent(10011001) : 2^26
mantissa(11010110111100110100011): 1.8396495580673218
Value actually stored in float: 1.8396495580673218 * 2^26 = 123456792
Error due to conversion: 3
- 以下是编译器实际工作方式的详细介绍:https://gcc.godbolt.org/z/C4YyKe
int main()
{
float t = 123456789;
}
main:
push rbp
mov rbp, rsp
movss xmm0, DWORD PTR .LC0[rip]
movss DWORD PTR [rbp-4], xmm0
mov eax, 0
pop rbp
ret
.LC0:
.long 1290500515 //(0x4CEB79A3)
关于C 具有基本整数值的 float 给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53620981/