精度损失 - int ->浮动或双 [英] Loss of precision - int -> float or double

查看:20
本文介绍了精度损失 - int ->浮动或双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一道考试题要复习,题目是 4 分.

I have an exam question I am revising for and the question is for 4 marks.

在 java 中,我们可以将 int 分配给 double 或 float".这会丢失信息吗?为什么?

"In java we can assign a int to a double or a float". Will this ever lose information and why?

我之所以这么说是因为整数通常是固定长度或大小的——存储数据的精度是有限的,而以浮点数存储信息可以是无限的,本质上我们会因此而丢失信息

I have put that because ints are normally of fixed length or size - the precision for storing data is finite, where storing information in floating point can be infinite, essentially we lose information because of this

现在我有点粗略地知道我是否在这里击中了正确的区域.我很确定它会失去精确度,但我无法确切说明原因.请问我能得到一些帮助吗?

Now I am a little sketchy as to whether or not I am hitting the right areas here. I very sure it will lose precision but I can't exactly put my finger on why. Can I get some help, please?

推荐答案

在 Java 中 Integer 使用 32 位来表示它的值.

In Java Integer uses 32 bits to represent its value.

在 Java 中,FLOAT 使用 23 位尾数,因此大于 2^23 的整数将被截断其最低有效位.例如 33554435(或 0x200003)将被截断为大约 33554432 +/- 4

In Java a FLOAT uses a 23 bit mantissa, so integers greater than 2^23 will have their least significant bits truncated. For example 33554435 (or 0x200003) will be truncated to around 33554432 +/- 4

在 Java 中,DOUBLE 使用 52 位尾数,因此能够表示 32 位整数而不会丢失数据.

In Java a DOUBLE uses a 52 bit mantissa, so will be able to represent a 32bit integer without lost of data.

另请参阅维基百科上的浮点"

See also "Floating Point" on wikipedia

这篇关于精度损失 - int ->浮动或双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆