难以输出返回double的String

时间:2017-10-06 05:19:12

标签: java

下面是一个程序,我输出带有返回的double值的String消息有困难。非常感谢任何帮助我不知道从哪里开始。我可能过度思考或过度看待一个简单的解决方案。谢谢!

预期输出为:

average = 12.5  
average = 7.63  
average = 6.96  

但是我的程序正在输出:

12.5  
7.63  
6.96

这是我的代码:

class Test2{
       public static void main(String[] args){
          int i, j;  
          double di, dj, dk;  
          i = 20;  
          j = 5;  
          Overload ol = new Overload();  
          System.out.println(ol.findAverage(i, j));  
          di = 14.29;  
          dj = 0.97;  
          System.out.println(ol.findAverage(di, dj));  
          di = 3.51;  
          dj = 13.5;  
          dk = 3.87;  
          System.out.println(ol.findAverage(di, dj, dk));
       }
    }

    class Overload {
       private int i, j;
       private double di, dj, dk;
       private double average;

       public double findAverage(int i, int j) {
          average = ((i + j) / 2.0);    
          return average;
       } 

       public double findAverage(double di, double dj) { 
          average = (di + dj) / 2.0; 
          return average;
       } 

       public double findAverage(double di, double dj, double dk) { 
          average = (di + dj + dk) / 3.0; 
          return average;
       }

       public String findAverage() {
          return "average = " + average;
       }
    }

1 个答案:

答案 0 :(得分:3)

致电时:

System.out.println(ol.findAverage(i, j));  

在后面,你正在打电话

public double findAverage(int i, int j) {
      average = ((i + j) / 2.0);    
      return average;
   } 

此函数仅返回双重计算

如果您想要正确的输出,只需执行以下操作:

ol.findAverage(i, j);
System.out.println(ol.findAverage());