用java计算平均值

发布于 2024-11-28 13:48:40 字数 630 浏览 3 评论 0 原文

编辑:我已经编写了平均值代码,但我不知道如何制作它,以便它也使用我的 args.length 中的 ints

我需要编写一个 java 程序来计算:

  1. 平均值中读取的整数数量
  2. - 不一定是整数!

注意:我不想计算数组的平均值,而是计算 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)

任何人都可以引导我走向正确的方向吗?或者举一个例子来指导我以正确的方式塑造这段代码?

提前致谢。

EDIT: I've written code for the average but I don't know how to make it so that it also uses ints from my args.length rather than the array.

I need to write a java program that can calculate:

  1. the number of integers read in
  2. the average value – which need not be an integer!

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

Currently I have written this:

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?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

缪败 2024-12-05 13:48:40

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

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 数组。这似乎是一个字符串数组,因此相应地更新了答案。

更新

正如zoxqoj正确指出的那样,上面的代码没有考虑整数/双精度溢出。尽管我假设输入值足够小而不会出现该问题,但这里有一个用于非常大的输入值的代码片段:

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

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

  • 精度保持不变,使用 double 你会随着数学运算的数量逐渐失去精度(或者根本无法获得精确的精度,具体取决于数字)
  • 溢出的可能性实际上被消除了。但请注意,BigDecimal 可能比适合 doublelong 的大小。

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 );

Note that the loop can also be simplified:

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

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

Update:

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):

  • 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.
伪心 2024-12-05 13:48:40
int values[] = { 23, 1, 5, 78, 22, 4};

int sum = 0;
for (int i = 0; i < values.length; i++)
    sum += values[i];

double average = ((double) sum) / values.length;
int values[] = { 23, 1, 5, 78, 22, 4};

int sum = 0;
for (int i = 0; i < values.length; i++)
    sum += values[i];

double average = ((double) sum) / values.length;
小镇女孩 2024-12-05 13:48:40

for (int i = 0; i<args.length -1; ++i)
    count++;

基本上再次计算了 args.length,只是不正确(循环条件应该是 i)。为什么不直接使用 args.length (或 nums.length )呢?

否则你的代码看起来没问题。虽然看起来您想从命令行读取输入,但不知道如何将其转换为数字数组 - 这是您真正的问题吗?

This

for (int i = 0; i<args.length -1; ++i)
    count++;

basically computes args.length again, just incorrectly (loop condition should be i<args.length). Why not just use args.length (or nums.length) directly instead?

Otherwise your code seems OK. Although it looks as though you wanted to read the input from the command line, but don't know how to convert that into an array of numbers - is this your real problem?

不可一世的女人 2024-12-05 13:48:40

这看起来似乎很古老,但 Java 从那时起就已经发展起来了。介绍了 Streams & Java 8 中的 Lambdas。因此可能会帮助每个想要使用 Java 8 功能来做到这一点的人。

  • 在你的情况下,你想将 String[] 的 args 转换为 double
    或整数。您可以使用 Arrays.stream() 来完成此操作。一旦有了字符串数组元素流,您就可以使用mapToDouble(s -> Double.parseDouble(s))它将字符串流转换为双精度流。
  • 然后如果你想自己控制增量计算,可以使用 Stream.collect(supplier,accumulator,combiner) 来计算平均值。这是 一些很好的例子
  • 如果不想增量求平均值,可以直接使用Java的Collectors.averagingDouble(),它直接计算并返回平均值。一些 这里有示例

It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.

  • In your case, you want to convert args which is String[] into double
    or int. You can do this using Arrays.stream(<arr>). Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s)) which will convert stream of Strings into stream of doubles.
  • Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
  • If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.
徒留西风 2024-12-05 13:48:40
 System.out.println(result/count) 

你不能这样做,因为 result/count 不是 String 类型,而 System.out.println() 仅接受 String 参数。也许尝试:

double avg = (double)result / (double)args.length
 System.out.println(result/count) 

you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:

double avg = (double)result / (double)args.length
无可置疑 2024-12-05 13:48:40

对于 1. 读入的整数数量,您可以使用数组的 length 属性,例如 :

int count = args.length

,它给出数组中的元素数量。
2.计算平均值:
你正在以正确的方式做事。

for 1. the number of integers read in, you can just use length property of array like :

int count = args.length

which gives you no of elements in an array.
And 2. to calculate average value :
you are doing in correct way.

友欢 2024-12-05 13:48:40

而不是:

int count = 0;
for (int i = 0; i<args.length -1; ++i)
    count++;
System.out.println(count);

 }

你可以只是

int count = args.length;

平均值是你的参数的总和除以你的参数的数量。

int res = 0;
int count = args.lenght;

for (int a : args)
{
res += a;
}
res /= count;

你也可以缩短这段代码,我会让你尝试询问你是否需要帮助!

这是我的第一个答案,如果有问题请告诉我!

Instead of:

int count = 0;
for (int i = 0; i<args.length -1; ++i)
    count++;
System.out.println(count);

 }

you can just

int count = args.length;

The average is the sum of your args divided by the number of your args.

int res = 0;
int count = args.lenght;

for (int a : args)
{
res += a;
}
res /= count;

you can make this code shorter too, i'll let you try and ask if you need help!

This is my first answerso tell me if something wrong!

感性不性感 2024-12-05 13:48:40

如果您尝试从命令行参数获取整数,您将需要这样的东西:

public static void main(String[] args) {
    int[] nums = new int[args.length];
    for(int i = 0; i < args.length; i++) {
        try {
            nums[i] = Integer.parseInt(args[i]);
        }
        catch(NumberFormatException nfe) {
            System.err.println("Invalid argument");
        }
    }

    // averaging code here
}

至于实际的平均代码,其他人建议了如何调整它(所以我不会重复他们所说的内容) )。

编辑:实际上,最好将其放在上面的循环中,根本不使用 nums 数组

If you're trying to get the integers from the command line args, you'll need something like this:

public static void main(String[] args) {
    int[] nums = new int[args.length];
    for(int i = 0; i < args.length; i++) {
        try {
            nums[i] = Integer.parseInt(args[i]);
        }
        catch(NumberFormatException nfe) {
            System.err.println("Invalid argument");
        }
    }

    // averaging code here
}

As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).

Edit: actually it's probably better to just put it inside the above loop and not use the nums array at all

时光无声 2024-12-05 13:48:40

我将向您展示两种方法。如果您的项目中不需要大量统计数据,只需实施以下操作即可。

public double average(ArrayList<Double> x) {
    double sum = 0;
    for (double aX : x) sum += aX;
    return (sum / x.size());
}

如果您计划进行大量统计,最好不要重新发明轮子。那么为什么不看看 http://commons.apache.org/proper/ commons-math/userguide/stat.html

你会爱上真正的爱!

I'm going to show you 2 ways. If you don't need a lot of stats in your project simply implement following.

public double average(ArrayList<Double> x) {
    double sum = 0;
    for (double aX : x) sum += aX;
    return (sum / x.size());
}

If you plan on doing a lot of stats might as well not reinvent the wheel. So why not check out http://commons.apache.org/proper/commons-math/userguide/stat.html

You'll fall into true luv!

不交电费瞎发啥光 2024-12-05 13:48:40
public class MainTwo{
    public static void main(String[] arguments) {
        double[] Average = new double[5];
        Average[0] = 4;
        Average[1] = 5;
        Average[2] = 2;
        Average[3] = 4;
        Average[4] = 5;
        double sum = 0;
        if (Average.length > 0) {
            for (int x = 0; x < Average.length; x++) {
                sum+=Average[x];
                System.out.println(Average[x]);
            }
            System.out.println("Sum is " + sum);
            System.out.println("Average is " + sum/Average.length);
      }
   }
}
public class MainTwo{
    public static void main(String[] arguments) {
        double[] Average = new double[5];
        Average[0] = 4;
        Average[1] = 5;
        Average[2] = 2;
        Average[3] = 4;
        Average[4] = 5;
        double sum = 0;
        if (Average.length > 0) {
            for (int x = 0; x < Average.length; x++) {
                sum+=Average[x];
                System.out.println(Average[x]);
            }
            System.out.println("Sum is " + sum);
            System.out.println("Average is " + sum/Average.length);
      }
   }
}
嗼ふ静 2024-12-05 13:48:40

// 问题:让,使用循环从键盘中取出 10 个整数,并将它们的平均值打印在屏幕上。
// 这里他们要求用户使用循环输入 10 个整数并对这些数字进行平均。所以在我看来,java 的正确答案如下:-

import java.util.Scanner;

public class averageValueLoop {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            int sum = 0;
            for (int i = 0; i < 10; i++){
                System.out.print("Enter a number: ");
                sum = sum + sc.nextInt();
            }

            double average = sum / 10;
            System.out.println("Average is " + average);

        }

    }

}

// question: let, Take 10 integers from keyboard using loop and print their average value on the screen.
// here they ask user to input 10 integars using loop and average those numbers.so the correct answer in my perspective with java is below:-

import java.util.Scanner;

public class averageValueLoop {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            int sum = 0;
            for (int i = 0; i < 10; i++){
                System.out.print("Enter a number: ");
                sum = sum + sc.nextInt();
            }

            double average = sum / 10;
            System.out.println("Average is " + average);

        }

    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文