問題描述
我有一道考試題要復習,題目是 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 ->浮動或雙的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!