如何操作数组。求其平均值。初级的Java [英] How to manipulate arrays. Find the average. Beginner Java

查看:172
本文介绍了如何操作数组。求其平均值。初级的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个家庭作业,我想知道,如果有人可以帮助我,因为我是新来的Java和编程很憋屈的一个问题。现在的问题是:

I have a homework assignment and I was wondering if anyone could help me as I am new to Java and programming and am stuck on a question. The question is:

第一种方法找到一个整数数组的元素的平均

The first method finds the average of the elements of an integer array:

public double average(int[] data)

即,给定一个整数数组,数据,计算出其元件的平均是返回的平均值。例如,平均{1,3,2,5,8}为3.8。

That is, given an integer array, data, calculate the average of its elements are return the average value. For example, the average of {1, 3, 2, 5, 8} is 3.8.

这是我迄今所做的:

public double average(int[] data) {  
    int sum = 0;

    while(int i=0; i < data.length; i++) 

    sum = sum + data[i]; 
    double average = sum / data.length;; 

    System.out.println("Average value of array element is " " + average);
}

在编译它,我得到的 INT I = 0 部分说的.class预期的错误消息。任何帮助将是AP preciated。

When compiling it I get an error message at the int i=0 part saying '.class expected'. Any help would be appreciated.

推荐答案

使用增强的话会更好:

int sum = 0;
for (int d : data) sum += d;

这可能会给你一个巨大的惊喜另一件事情是错误的结果,你会从

Another thing that will probably give you a big surprise is the wrong result that you will obtain from

double average = sum / data.length;

原因:在右边你有整数除法和Java不会自动将其提升到浮点除法。它会计算总和/ data.length的整数商然后才推动该整数到双击。一个解决方案是

Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length and only then promote that integer to a double. A solution would be

double average = 1.0d * sum / data.length;

这将强制分红成双击,它会自动传播到除数。

This will force the dividend into a double, which will automatically propagate to the divisor.

这篇关于如何操作数组。求其平均值。初级的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆