查找数组元素的总和,Java

时间:2016-01-10 23:35:49

标签: java arrays

在尝试获取数组中元素的总和和平均值时,有人能帮我弄清楚我做错了什么吗?我的任务是:你正在为波士顿马拉松赛做准备。为了准备,你需要训练10周,每周运行越来越多的里程,从第一周运行至少2英里到第10周运行26英里。一个问题是要找到总数的总和英里跑了十多个星期,平均里程超过十周,而我所拥有的将会毫无错误地执行,但总和是26.000000000004,我知道这是错误的。任何建议将不胜感激。我是新手。

    public class arrayTest
    {
    public static void main(String[] args) {

          double[] miles = new double [10];

                double milesPerWeek = 26.0 / 10;
                double totalMiles = 0;
                double sum = 0;
                double average = 0;

                System.out.println("Week\tMiles");

                for (int i = 0; i < miles.length; i++)
                {
                      miles[i] += milesPerWeek;
                      totalMiles += miles[i];

                  System.out.println("Week " + i + " miles " + totalMiles);
                     }
                for (int i = 0; i < miles.length; i++)
                {              
                      sum = sum + miles[i];
                      average = sum / miles.length;
                   }
                  System.out.print("the sum of the miles ran is: " + sum + "\n");

                  System.out.print("the average miles ran is: " + average);
                }
          }
    The result reads:
    Week    Miles
    Week 0 miles 2.6
    Week 1 miles 5.2
    Week 2 miles 7.800000000000001
    Week 3 miles 10.4
    Week 4 miles 13.0
    Week 5 miles 15.6
    Week 6 miles 18.2
    Week 7 miles 20.8
    Week 8 miles 23.400000000000002
    Week 9 miles 26.000000000000004
    the sum of the miles ran is: 26.000000000000004
    the average miles ran is: 2.6000000000000005

2 个答案:

答案 0 :(得分:0)

尝试使用printf格式化输出,以便您可以控制输出的格式。

System.out.printf("Week " + i + " miles %.2f\n", totalMiles);

输出

Week    Miles
Week 0 miles 2,60
Week 1 miles 5,20
Week 2 miles 7,80
Week 3 miles 10,40
Week 4 miles 13,00
Week 5 miles 15,60
Week 6 miles 18,20
Week 7 miles 20,80
Week 8 miles 23,40
Week 9 miles 26,00

答案 1 :(得分:-2)

您的问题是Java double原语在处理浮点的方式上并不精确。 (有关该问题的更多信息,请参阅this question。)

如果您想避免此问题,请查看BigDecimal类。

如果你不想改变它,你几乎无能为力。这是语言本身的问题,而不是你正在做的任何事情。