【问题标题】:Sum and Averages of an Array数组的总和和平均值
【发布时间】:2024-01-19 07:48:01
【问题描述】:

我正在为我的大学课程研究一个数组问题,我正在尝试找到一个数组的总和和平均值。这是我到目前为止的代码。

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

   //declare the array to have 10 items for 10 weeks
   //also declare sum as an int and average as a double to accommodate for decimal points

      int[] weeks = new int[10];
      int sum = 0;
      double average = 0;

   //declare the array values

      weeks[0]= 2;
      weeks[1]= 4;
      weeks[2]= 8;
      weeks[3]= 10;
      weeks[4]= 14;
      weeks[5]= 16;
      weeks[6]= 20;
      weeks[7]= 22;
      weeks[8]= 24;
      weeks[9]= 26;

   // determine sum of the array values

     for (int index = 0; index < weeks.length; index++) weeks[index] = index;
        sum = sum + weeks[index];
        System.out.println("The total miles ran in 10 weeks is " + sum);

   // determine the average of the array values

     if (weeks.length != 0)
        average = sum / weeks.length;
     else
        average = 0;

     System.out.println("The average of the miles ran in 10 weeks is " + average);
     }
}

我知道平均值有效,但我坚持总和。我遇到的问题是我似乎无法初始化数组中的值,以便为它们提供总和。我做错了什么或者我错过了什么?

【问题讨论】:

  • 也许您想删除循环语句weeks[index] = index;?这根本没有意义。此外,下一行sum = sum + weeks[index]; 似乎是循环语句。
  • 您的 for 循环中只有一条语句:weeks[index] = index;
  • 刚刚更新了我的答案,也解决了你的精度问题,你可以去看看。

标签: java arrays sum average


【解决方案1】:

您的代码中有两个问题;

A) For 循环赋值

第一个作业不用做,把sum加到week[index]上就可以了;

    for (int index = 0; index < weeks.length; index++)
        sum = sum + weeks[index];

B) 计算平均值

Sum 被定义为int,它是一个原始整数,因此,将整数除以整数,输出是一个不精确的整数。除法 (45/10) 的输出被转换为整数,然后分配给 double,四舍五入为 4,然后再次转换为 double,结果为 '4.0'。

为避免这种不精确的结果,请将 sum 转换为如下所示的 double;

average = (double)sum / weeks.length;

您的代码的更正版本如下;

演示

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

        // declare the array to have 10 items for 10 weeks
        // also declare sum as an int and average as a double to accommodate for
        // decimal points

        int[] weeks = new int[10];
        int sum = 0;
        double average = 0;

        // declare the array values

        weeks[0] = 2;
        weeks[1] = 4;
        weeks[2] = 8;
        weeks[3] = 10;
        weeks[4] = 14;
        weeks[5] = 16;
        weeks[6] = 20;
        weeks[7] = 22;
        weeks[8] = 24;
        weeks[9] = 26;

        // determine sum of the array values
        for (int index = 0; index < weeks.length; index++)
            sum = sum + weeks[index];

        System.out.println("The total miles ran in 10 weeks is " + sum);

        // determine the average of the array values
        if (weeks.length != 0)
            average = (double)sum / weeks.length;
        else
            average = 0;

        System.out.println("The average of the miles ran in 10 weeks is " + average);
    }
}

输出

The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6

以及范围说明

关于范围的最后一点说明,请查看此代码;

 for (int index = 0; index < weeks.length; index++)
    weeks[index] = index;
    sum = sum + weeks[index];
    System.out.println("The total miles ran in 10 weeks is " + sum);

for-loop中,由于没有使用括号,因此编译器在循环的scope中只考虑for-loop下的第一条语句。这就是为什么对于下一行,编译器会给出关于索引的错误,因为索引是在 for-loopscope 内定义的。

【讨论】:

  • 还有weeks[index] = index;覆盖之前分配的所有值的问题。
  • 非常感谢!我真的很感谢我没有得到的分解解释!
  • 我很高兴,顺便说一句,我还在我的回答中添加了一条注释,只是为了指出为什么编译器会警告索引。编译器对此发出警告,因为编译器不考虑在 for 循环内部。
  • 酷我真的很感激!再次感谢您的所有帮助!
【解决方案2】:

您需要在 for 循环中使用方括号。目前你的代码是这样评估的:

for (int index = 0; index < weeks.length; index++) 
{
    weeks[index] = index;
}
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);

你希望你的代码像这样评估

for (int index = 0; index < weeks.length; index++) 
{
    weeks[index] = index; //logical issue, what does this line achieve?
    sum = sum + weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);

这至少会解决您的程序问题,但您仍然需要查看您的逻辑。尝试使用断点来调试您的代码。

【讨论】:

  • 你真的认为weeks[index] = indexSystem.out.println(...)这两个语句属于循环吗?第一个覆盖之前设置的所有值。我认为,他必须简单地删除那个。
  • @Seelenvirtuose 我同意。我编辑了我的答案,指出它将解决程序问题,但像你提出的逻辑问题是另一个问题
  • 谢谢。当您是 Java 新手时,语法真的很难。感谢@NoamHacker 的帮助
【解决方案3】:

在 Java 8 中实现此目的的一个非常简单的方法是使用内置机制来收集统计信息:

int[] weeks = {3, 4, 6, 9, 10};
IntSummaryStatistics stats = IntStream.of(weeks).summaryStatistics();
System.out.println("sum = " + stats.getSum() + "; average = " + stats.getAverage());

【讨论】:

  • 不需要写 getsum 或取平均值我在输出中自动得到了
  • 使用 summaryStatistics() 就足够了。
  • 是的IntSummaryStatistics 有一个明智的toString - 但问题要求求和和平均值,所以我展示了如何提取它们。
【解决方案4】:
for (int i = 0;i < weeks.length) {
    sum += weeks[i];
}

System.out.println("Sum is:" + sum);

【讨论】:

  • 他要求找到平均值而不是总和需要将最后一行更改为 sum/weeks.length。
【解决方案5】:

首先,您根本不需要这行weeks[index] = index;。 对于平均值,如果您想将平均值设为双倍,您必须将总和设为两倍,因为您已将总和声明为 int。

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

   //declare the array to have 10 items for 10 weeks
   //also declare sum as an int and average as a double to accommodate for decimal points

      int[] weeks = {2,4,8,10,14,16,20,22,24,26};
      int sum = 0;
      double average = 0;

   // determine sum of the array values

     for (int index = 0; index < weeks.length; index++) 
         //weeks[index] = index;
         sum = sum + weeks[index];
         System.out.println("The total miles ran in 10 weeks is " + sum);

   // determine the average of the array values

     if (weeks.length != 0)
        average = (double)sum / weeks.length;
     else
        average = 0;

     System.out.println("The average of the miles ran in 10 weeks is " + average);
     }
}

10 周内跑的总里程为 146 英里

10 周的平均跑步里程为 14.6 英里

【讨论】:

    【解决方案6】:

    像这样将一个数字数组相加并除以 n 以获得平均值不会得到正确的值 - 您不应该使用整数除法来计算平均值。 此外,这种方法可能适用于所示示例,但通常不适用。例如,尝试使用此代码查找这两个值的平均值:(INT_MAX-6) 和 (INT_MAX-2)。

    【讨论】:

      【解决方案7】:

      更正后的代码。在计算平均值时,您将变量加倍,否则您将得到平均值作为整数

      public class Mod55 {
      
          public static void main(String args[]) {
      
              //declare the array to have 10 items for 10 weeks
              //also declare sum as an int and average as a double to accommodate for decimal points
              int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
              int sum = 0;
              double average = 0;
      
              // determine sum of the array values
              for (int index = 0; index < weeks.length; index++) {
                  sum += weeks[index];
              }
              System.out.println("The total miles ran in 10 weeks is " + sum);
      
              // determine the average of the array values
              if (weeks.length != 0) {
                  average = (double)sum / weeks.length;
              } else {
                  average = 0;
              }
      
              System.out.println("The average of the miles ran in 10 weeks is " + average);
          }
      }
      

      Java8 你可以像这样实现同样的事情。

              int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
              int sum = Arrays.stream(weeks)
                       .sum();
              double average = Arrays.stream(weeks).average().orElse(0);
      

      【讨论】:

        【解决方案8】:

        您可以使用 lambdas 找到这个方便。代码看起来像这样。

        int weeks[] = {1,2,3,4};
        List<Integer> asd = IntStream.of(weeks).boxed().collect(Collectors.toList());
        //asd.forEach(System.out::println);
        //this outputs average
        System.out.println(asd.stream().mapToDouble(val -> val).sum()/asd.size());
        //this outputs sum
        System.out.println(asd.stream().mapToInt(val -> val).sum());
        //another way to achieve this thanks to commenter
        System.out.println(IntStream.of(asd).summaryStatistics());
        

        【讨论】:

        • 别忘了导入 java.util.stream.Collectors;导入 java.util.stream.IntStream;
        • 导入 java.util.ArrayList;导入 java.util.Arrays;导入 java.util.List;
        • 实际上它比 Java 8 中的更简单:IntStream.of(weeks).summaryStatistics()。然后在结果上使用getAveragegetSum 等。
        • 你能发布示例链接吗?我在尝试时遇到了一些错误。
        • 我会发布一个答案给你看
        最近更新 更多