問(wèn)題描述
我有兩個(gè)整數(shù) x
和 y
.我需要計(jì)算 x/y
作為結(jié)果,我想獲得浮動(dòng).例如,作為 3/2
的結(jié)果,我想要 1.5.我認(rèn)為最簡(jiǎn)單(或唯一)的方法是將 x
和 y
轉(zhuǎn)換為浮點(diǎn)類(lèi)型.不幸的是,我找不到一個(gè)簡(jiǎn)單的方法來(lái)做到這一點(diǎn).你能幫我解決這個(gè)問(wèn)題嗎?
I have two integers x
and y
. I need to calculate x/y
and as outcome I would like to get float. For example as an outcome of 3/2
I would like to have 1.5. I thought that easiest (or the only) way to do it is to convert x
and y
into float type. Unfortunately, I cannot find an easy way to do it. Could you please help me with that?
推薦答案
您只需要將至少一個(gè)操作數(shù)強(qiáng)制轉(zhuǎn)換為浮點(diǎn)數(shù):
You just need to cast at least one of the operands to a float:
float z = (float) x / y;
或
float z = x / (float) y;
或(不必要的)
float z = (float) x / (float) y;
這篇關(guān)于如何在 Java 中將整數(shù)轉(zhuǎn)換為浮點(diǎn)數(shù)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!