2015-09-13 17 views
-1

你好我對Java只有很新的感覺,只有3天了,而且我正努力爲這個程序輸出十進制數。Java靜態值不輸出小數「可能有損於從double到int的轉換」

static int temp1=66-32*(5/9); 

static int temp2=95-32*(5/9); 

static int temp3=85-32*(5/9); 

static int temp4=65-32*(5/9); 

static int temp5=(0-32)*(.55); 


public static void main(String[] args) { 
    System.out.println("Today's temperature is 66 degrees Fahrenheit. In Celsius it is:"+temp1); 
    System.out.println("The temperature is 95 degress Fahrenheit in Celsius is:"+temp2); 
    System.out.println("The temperature is 85 degrees Fahrenheit in Celsius is:"+temp3); 
    System.out.println("The temperature is 65 degrees Fahrenheit in Celsius is:"+temp4); 
    System.out.println("The temperature is 0 degrees Fahrenheit in Celsius is:\n"+temp5); 
} 

回答

-1

您正在使用整數。整數不能顯示小數。嘗試使用double來代替。雙精度最高可達16位數字。

static double yourTemp = ... 
+0

雙爲您提供了最多的精度16位可能會超過小數點後16位。 –

+0

哦,我很抱歉我的錯誤答案 – grahan

+0

你可以更正你的答案,我會刪除我的評論。 –

1

5/9 == 0整數除法爲5除以9不會給5個餘數。

您的公式也不正確。您首先需要執行-32

int temp1 = (66-32) * 5/9; 

這會給你舍入的最接近的整數值。

double temp1 = (66 - 32) * 5/9.0; 
// print temp1 to two decimal places. 
System.out.printf("Temp1= %.2f%n", temp1); 

這會給你兩位小數。使用/ 9.0意味着使用浮點除法,因爲9.0是一個雙精度值。到目前爲止,它沒什麼區別,但你可以寫。

double temp1 = (66.0 - 32.0) * 5.0/9.0; 

並得到相同的結果。

0

所有首先,如果你想接收小數輸出,你將不得不改變數據類型從intdouble,因爲double是用來聲明變量保持十進制值的數據類型。所以把所有的int改爲double的。

第二個:你認爲(5/9)應該輸出類似0.555的東西,對嗎?因爲這是你在衝入計算器時得到的結果。但不是!在Java中,(5/9)以INTEGER轉換計算,因爲5和9都是INTEGER。這意味着,當Java計算(5/9)時,它只返回小數點左邊的數字,因爲它知道不處理小數。 0.555中小數點剩下的數字是多少?很明顯,0.因此,返回(5/9)的答案將爲0,這意味着您的temp1temp2,temp3temp4都將爲0,因爲0乘以任何數都是0.對於temp5,您包括小數點指向.55 - 因此,這個計算很好。

那麼...什麼?如果你想在屏幕上打印一個十進制答案,你可以做兩件事之一:在每個數字的末尾添加一個小數點。所以製作它66.0-32.0 * (5.0/9.0)。或者,你可以簡單地在(5/9)上添加一個(double)強制轉換。所以像這樣:((double)5/9)。請確保你到底格式設置爲給定的,否則將無法正常工作,你可能仍然得到0。這裏是低於成品代碼:

public class printDecimal{ 
    static double temp1 = 66-32 * ((double)5/9); 
    static double temp2 = 95-32 * ((double)5/9); 
    static double temp3 = 85-32 * ((double)5/9); 
    static double temp4 = 65-32 * ((double)5/9); 
    static double temp5 = (0-32) * ((double)5/9); 

    public static void main(String[] args){ 
     System.out.println("66 degrees Fahrenheit in Celsius is: "+temp1); 
     System.out.println("95 degrees Fahrenheit in Celsius is: "+temp2); 
     System.out.println("85 degrees Fahrenheit in Celsius is: "+temp3); 
     System.out.println("65 degrees Fahrenheit in Celsius is: "+temp4); 
     System.out.println("0 degrees Fahrenheit in Celsius is: "+temp5); 
    } 
} 
相關問題