我有2个类DigitMath.java和DigitMathRunner.java,实验室要求的设置使用DigitMathRunner作为DigitMath的启动器。

我的代码的目的是显示“平均值”,然后将其输出到句子中。
编译器未给出错误,但输出如下。

> >

run DigitMathRunner

234 has a digit average of 0.0

10000 has a digit average of 0.0

111 has a digit average of 0.0

9005 has a digit average of 0.0

84645 has a digit average of 0.0

8547 has a digit average of 0.0

123456789 has a digit average of 0.0
>


这是DigitMath.java的代码

import static java.lang.System.*;

public class DigitMath
 {
  private int number;
  private int count;
  private int s;
  private int sum;
  private int input;
  private double average;



   public DigitMath()
 {
  number = 0;
  sum=0;
  count = 0;
  input = 0;
 }


  public DigitMath(int s)
  {
    number = s;
    input = s;
  }


   public void setNums(int s)
  {
     number = s;
     input = s;
  }


   public int sumDigits()
  {
     int sum=0;
     while(input > 0)
   {
    sum += input % 10;
    input /= 10;
   }
     return sum;
  }


 public int countDigits()
 {
   count = (int)(Math.log10(number)+1);
   return count;
 }


 public double averageDigits()
 {
  double average = sum/count;
  return average;
 }


 public int output()
 {
   System.out.println(""+number +" has a digit average of "+""+average);
   return number;
 }

 }


下一个代码块是Runner。

//Name - Seth Garcia
//Date - 5/12/16
//Class - 3rd Period Monaghan
//Lab  - DigitMath

import static java.lang.System.*;

public class DigitMathRunner
{
 public static void main( String args[] )
{
   DigitMath test = new DigitMath();

      test.setNums(234);
      test.sumDigits();
      test.countDigits();
      test.averageDigits();
      test.output();

      test.setNums(10000);
      test.sumDigits();
      test.countDigits();
      test.averageDigits();
      test.output();

      test.setNums(111);
      test.sumDigits();
      test.countDigits();
      test.averageDigits();
      test.output();

      test.setNums(9005);
      test.sumDigits();
      test.countDigits();
      test.averageDigits();
      test.output();

      test.setNums(84645);
      test.sumDigits();
      test.countDigits();
      test.averageDigits();
      test.output();

      test.setNums(8547);
      test.sumDigits();
      test.countDigits();
      test.averageDigits();
      test.output();

      test.setNums(123456789);
      test.sumDigits();
      test.countDigits();
      test.averageDigits();
      test.output();
 }
}


我也是Highschool的Computer Science 1的学生,如果我的代码不好,请告诉我如何改进,谢谢。

最佳答案

可变阴影是您的问题。

double average = sum/count;


请删除double

和力浮点除法

average = sum/(double)count;


类似的问题在sumDigits()

此外,由于private double average是一个计算值,因此可以完全删除。

public double averageDigits()
{
    return sum/(double)count;
}


并在output方法而不是average中使用该方法

关于java - 我的平均值/输出返回了0.0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37188305/

10-10 21:54