問題描述
我有一道考試題要復(fù)習(xí),題目是 4 分.
I have an exam question I am revising for and the question is for 4 marks.
在 java 中,我們可以將 int 分配給 double 或 float".這會(huì)丟失信息嗎?為什么?
"In java we can assign a int to a double or a float". Will this ever lose information and why?
我之所以這么說是因?yàn)檎麛?shù)通常是固定長(zhǎng)度或大小的——存儲(chǔ)數(shù)據(jù)的精度是有限的,而以浮點(diǎn)數(shù)存儲(chǔ)信息可以是無限的,本質(zhì)上我們會(huì)因此而丟失信息
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
現(xiàn)在我有點(diǎn)粗略地知道我是否在這里擊中了正確的區(qū)域.我很確定它會(huì)失去精確度,但我無法確切說明原因.請(qǐng)問我能得到一些幫助嗎?
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 中,F(xiàn)LOAT 使用 23 位尾數(shù),因此大于 2^23 的整數(shù)將被截?cái)嗥渥畹陀行?例如 33554435(或 0x200003)將被截?cái)酁榇蠹s 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 位尾數(shù),因此能夠表示 32 位整數(shù)而不會(huì)丟失數(shù)據(jù).
In Java a DOUBLE uses a 52 bit mantissa, so will be able to represent a 32bit integer without lost of data.
另請(qǐng)參閱維基百科上的浮點(diǎn)"
See also "Floating Point" on wikipedia
這篇關(guān)于精度損失 - int ->浮動(dòng)或雙的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!