2016-04-08 76 views
0

我是Java新手。我想打印出每15度間隔的sincostan值。Java:使用`Math.sin()時可能會失去精度`

public class W3Aufgabe5 { 
    public static void main(String[] args) { 

     System.out.printf("%6s%6s%6s%6s%n", "Angle", "Sin", "Cos", "Tan"); 
     System.out.println("------------------------"); 

     for (float angle = 0; angle <= 180; angle += 15) { 

      float sin = Math.sin(Math.toRadians(angle)); 
      float cos = Math.cos(Math.toRadians(angle)); 
      float tan = Math.tan(Math.toRadians(angle)); 

      System.out.printf("%6d%6d%6d%6d%n", angle, sin, cos, tan); 
     } 
    } 
} 

Math.x()線,編譯器打印

error: possible loss of precision
required: float
found: double

我真的不明白。爲什麼需要double,即使我一直在使用float

+0

你爲什麼會犯罪?除非你有實際的理由使用float,否則只需使用double。圖像處理或圖形。 – matt

回答

2

的三角函數sincostan,並toRadians都接受double作爲參數,並返回double。沒有超載接受float s並返回float s。將float傳遞給期望double的方法是合法的;它會被隱含地擴大。但是,如果將結果分配給float s,則無法隱式將double縮小到float

您可以顯式轉換的結果,float如果你想,但你得到更好的精度double,所以宣佈你sincostan變量double秒。

此外,格式說明符d表示整數值,而不是浮點值。使用format specifier f instead of d。當您打印它們時,您可能還希望在您的值之間放置一些間距。

+0

謝謝,這工作。我認爲格式說明符「f」和「d」與float和double有關 – flufflepuff

+0

否,'f'代表「定點」(格式),'e'代表指數或工程和'g'選擇最合適的。查看也是Java printf函數基礎的C printf格式字符串。 – LutzL

0

如果你看看API documentation,你會看到trig方法都會返回雙打。除非你真的需要浮動,否則最好的選擇是使用雙打。你失去了精度,因爲你必須強制你的雙重返回值爲浮動。