gpt4 book ai didi

java - 从我的平均/输出返回 0.0

转载 作者:行者123 更新时间:2023-11-29 10:10:37 26 4
gpt4 key购买 nike

我有 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();
}
}

我也在读高中计算机科学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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com