本文介紹了如何在 Java 中將整數轉換為浮點數?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有兩個整數 x
和 y
.我需要計算 x/y
作為結果,我想獲得浮動.例如,作為 3/2
的結果,我想要 1.5.我認為最簡單(或唯一)的方法是將 x
和 y
轉換為浮點類型.不幸的是,我找不到一個簡單的方法來做到這一點.你能幫我解決這個問題嗎?
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?
推薦答案
您只需要將至少一個操作數強制轉換為浮點數:
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;
這篇關于如何在 Java 中將整數轉換為浮點數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!