2013-12-11 80 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]); 
}