打印3个十进制数字表示双精度数

时间:2017-11-30 20:29:18

标签: java

我应该找到一堆给定数字的平均值,然后将它们全部加起来然后除以给出的数字,并且平均数必须有3个十进制数,所以对于45.0而言它将是45.000并且我的工作,但只有最后一个数字不是0。

import java.util.Scanner;
import static java.lang.System.*;

public class Average
{
   private String line;
   private double average, sum, count;

   public Average()
   {
     setLine("");
   }

   public Average(String s)
   {
     setLine(s);
   }

 public void setLine(String s)
 {
   line = s;
   sum = 0.0;
   count = 0.0;
   average = 0.0;
 }

 public double getCount()
 {
  int num = 0;
  while(num<line.length())
  {
    if(line.charAt(num) == 32)
    {
      count ++;
      num ++;
    }
    else
      num ++;
  }
  count ++;
  return count;
 }

 public double getSum()
 {
  Scanner bobby = new Scanner(line);
  while(bobby.hasNextInt())
    sum = sum + bobby.nextInt();
  return sum;
 }

 public double getAverage()
 {
  average = getSum()/getCount();
  average = average*1000;
  if(average%10>4)
  {
  average = Math.floor(average);
  average ++;
  average = average/1000.0;
  }
  else
  {
  average = Math.floor(average);
  average = average/1000.0;
  }
  return average;
  }

 public String getLine()
 {
  return line;
 }

 public String toString()
 {
  return "";
 }
}

这是我的跑步者档案

import java.util.Scanner;
import static java.lang.System.*;

public class AverageRunner
{
   public static void main( String args[] )
   {
     String s = "9 10 5 20";
     Average bob = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob.getAverage());
     System.out.println();

     s = "11 22 33 44 55 66 77";
     Average bob1 = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob1.getAverage());
     System.out.println();

     s = "48 52 29 100 50 29";
     Average bob2 = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob2.getAverage());
     System.out.println();

     s = "0";
     Average bob3 = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob3.getAverage());
     System.out.println();

     s = "100 90 95 98 100 97";
     Average bob4 = new Average(s);
     System.out.println("Find the average of the following numbers :: "+s);
     System.out.println("Average = " + " " + bob4.getAverage());
 }
}

1 个答案:

答案 0 :(得分:1)

使用DecimalFormat

DecimalFormat df = new DecimalFormat("#.000"); 
System.out.println("Nummber: " + df.format(1.2345));