在java中计算平均值 [英] Calculate average in java

查看:51
本文介绍了在java中计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为平均值编写了代码,但我不知道如何制作它以便它也使用我的 args.lengthints代码> 而不是数组.

我需要写一个可以计算的java程序:

I need to write a java program that can calculate:

  1. 读入的整数个数
  2. 平均值——不必是整数!

注意:我不想计算数组的平均值,而是计算 args 中的整数.

NOTE: I don't want to calculate the average from the array but the integers in the args.

目前我已经写了这个:

int count = 0;
for (int i = 0; i<args.length -1; ++i)
    count++;
    System.out.println(count);
}
    
int nums[] = new int[] { 23, 1, 5, 78, 22, 4};
double result = 0; //average will have decimal point
for(int i=0; i < nums.length; i++){
    result += nums[i];
}
System.out.println(result/count)

谁能指导我正确的方向?或者举个例子来指导我以正确的方式塑造这段代码?

Can anyone guide me in the right direction? Or give an example that guides me in the right way to shape this code?

提前致谢.

推荐答案

只需对您的代码稍作修改即可(为了清楚起见,对 var 进行了一些重命名):

Just some minor modification to your code will do (with some var renaming for clarity) :

double sum = 0; //average will have decimal point

for(int i=0; i < args.length; i++){
   //parse string to double, note that this might fail if you encounter a non-numeric string
   //Note that we could also do Integer.valueOf( args[i] ) but this is more flexible
   sum += Double.valueOf( args[i] ); 
}

double average = sum/args.length;

System.out.println(average );

注意循环也可以简化:

for(String arg : args){
   sum += Double.valueOf( arg );
}

OP 似乎想要使用 args 数组.这似乎是一个字符串数组,因此相应地更新了答案.

the OP seems to want to use the args array. This seems to be a String array, thus updated the answer accordingly.

更新:

正如 zoxqoj 正确指出的那样,上面的代码没有处理整数/双溢出.虽然我假设输入值足够小而不会出现这个问题,但这里有一个用于非常大的输入值的代码片段:

As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:

BigDecimal sum = BigDecimal.ZERO;
for(String arg : args){
  sum = sum.add( new BigDecimal( arg ) );
}

这种方法有几个优点(尽管速度有点慢,所以不要将它用于时间关键的操作):

This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):

  • 保持精度,使用 double 时,您会随着数学运算的数量逐渐降低精度(或者根本无法获得精确的精度,具体取决于数字)
  • 实际上消除了溢出的可能性.但是请注意,BigDecimal 可能大于适合 doublelong 的内容.
  • Precision is kept, with double you will gradually loose precision with the number of math operations (or not get exact precision at all, depending on the numbers)
  • The probability of overflow is practically eliminated. Note however, that a BigDecimal might be bigger than what fits into a double or long.

这篇关于在java中计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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