[英]Why am I getting zero when I multiply doubles?
我在調試時編寫了以下代碼: double hola = (1 / 2) * (double)x.height;
身高是一倍。 Hola只是一個臨時名稱。
當我調試時,我看到x.height = 1,hola = 0。
我做錯了什么? 我敢肯定我犯了一些非常簡單的錯誤。
同樣,當我刪除對x.height的雙重轉換時,我仍然得到hola = 0。
1 / 2
為零,余數為1。 零乘以零。
您是要寫1.0 / 2.0
嗎?
1
和2
均為int
,因此1/2
的結果將被強制轉換(截斷)為int。 0.5
> 0
。
您需要確保兩個操作數都支持小數點:
double hola = (1.0 / 2) * (double)x.height;
要么:
double hola = ((double)1 / 2) * (double)x.height;
將兩個整數相除將執行整數除法,這也會在相同類型(小數部分被截斷)中給出結果。在int參數上將非整數除法(此處為double)的方法是將至少一個參數顯式轉換為double 。 因此您的代碼將是:
double hola = (1 / (double)2) * (double)x.height;
要么
double hola = ((double)1 / 2) * (double)x.height;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.