2013-12-11 82 views
0

我有一個關於如何使用printf顯示的問題。我用過四次printf。前兩次和最後一次,它運行良好。第三個沒有。我希望它具有與其他值相同的格式。我怎樣才能解決這個問題?任何幫助將不勝感激。我使用的格式%15.2f顯示它,當我編譯並執行它,它只是給我:java顯示和使用printf格式化

run: 
    Mercury   Venus   Earth   Mars  Jupiter   Saturn   Uranus  Neptune   Pluto 
    2439.70  6051.90  6378.00  3402.50  71492.00  60270.00   25562.00  24774.00  1195.00 
330220000000000000000000.004868500000000000000000000.005973600000000001000000000.00641850000000000000000000.001898600000000000200000000000.00568459999999999960000000000.0086810000000000000000000000.00102430000000000000000000000.0013120000000000000000000.00 
     3.70   8.87   9.79   3.70   24.78   10.44   8.86   11.13   0.61 
BUILD SUCCESSFUL (total time: 0 seconds) 

下面是我的代碼(這裏我用printf進行第三次的地方的一個片段有額外的「 /「:

public static void printResults(String[] name, double[] radius, double[] mass, double[] gravity) 
{ 
     // fill in code here 
     for(int i = 0; i < name.length; i++){ 
      System.out.printf("%15s", name[i]); 
     } 
     System.out.println(); 

     for(int i = 0; i < radius.length; i++){ 
      System.out.printf("%15.2f", radius[i]); 
     } 
     System.out.println(); 
     ////////////////// 
     for(int i = 0; i < mass.length; i++){ 
      System.out.printf("%15.2f", mass[i]); 
     } 
     System.out.println(); 

     for(int i = 0; i < gravity.length; i++){ 
      System.out.printf("%15.2f", gravity[i]); 
     } 
     System.out.println(); 
} 

//print the gravity values to text file 
public static void printToFile(double[] gravity)throws IOException 
{ 
    // fill in code here 
} 

public static void main(String[] args)throws IOException 
{ 
    // Initialize variables 
    String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"}; 
    double[] radii = {2439.7, 6051.9, 6378, 3402.5, 71492, 60270, 25562, 24774, 1195}; 
    double[] masses = {3.3022 * Math.pow(10,23), 4.8685 * Math.pow(10,24), 5.9736 * Math.pow(10,24), 6.4185 * Math.pow(10,23), 
       1.8986 * Math.pow(10,27), 5.6846 * Math.pow(10,26), 8.6810 * Math.pow(10,25), 1.0243 * Math.pow(10,26), 1.312 * 
        Math.pow(10,22)}; 
    // or using big E notation: 
    // double [] mass = {3.30E23, 4.87E24, 5.97E24, 6.42E23, 1.90E27, 5.68E26, 8.68E25, 1.02E26, 1.27E22}; // See IMACS double lesson for big E notation 

    // Processing 
    double[] gravities = calcGravity(radii, masses); 
+1

質量值大於15位數。 '330220000000000000000000'是24位數字。您可以將這些列設置得更寬,或者對大衆使用更緊湊的表示形式:例如'3.3022e23'。 –

回答

1

輸出看起來怪異,因爲質量值是相當長的,尤其是當打印成十進制數的printf不會截斷超過給定字段寬度值

你可能想。反之印刷羣衆時使用e。它會pri用科學記數法表示這些數值可能更適合大數值。

for(int i = 0; i < mass.length; i++){ 
    System.out.printf("%15.2e", mass[i]); 
}