简体   繁体   English

如何计算数组的平均值

[英]How to calculate average of an Array

 import java.util.*; import java.lang.*; public class MyClass { String[] getdata() { Scanner in=new Scanner(System.in); System.out.print("Enter numbers to calculate their average (choose 5 to 10 numbers only : "); String[] a=in.nextLine().split(" "); return a; } double average(String[] num) { double avg; int tot=0; int[] numbers = new int[num.length]; int l=num.length; for(int j=0;j<l;j++) { tot=tot+numbers[j]; } avg=tot/l; return avg; } void results(String[] arr,double avg) { int[] numbers1=new int[arr.length]; int ll=arr.length; System.out.print("The average of the numbers "); for(int i=0;i<ll;i++) { numbers1[i]=Integer.parseInt(arr[i]); System.out.print(numbers1[i]+" "); } System.out.print("is "); System.out.printf("%.2f",avg); } public static void main(String args[]) { MyClass obj=new MyClass(); String[] x=obj.getdata(); double y=obj.average(x); obj.results(x,y); } } 

The code is running successfully but for any given output the average is showing as 0.00. 该代码已成功运行,但对于任何给定的输出,平均值均显示为0.00。

The code takes in integers with space between them and calculates the average and displays it 该代码接受整数,并在它们之间留有空格,并计算平均值并显示出来

Help me fix it. 帮我解决。 Thanks 谢谢

You do not initialize your numbers array inside average() method. 您没有在average()方法中初始化numbers数组。 Instead of tot=tot+numbers[j]; 代替tot=tot+numbers[j]; do the following 请执行下列操作

tot = tot + Integer.parseInt(num[j]);

And to avoid integer deletion change calculation if avg to the following 并避免整数删除更改计算,如果avg以下

avg = 1.0 * tot / l; //this will cast intermediate result of 1.0 * tot to double.

There are several issues with your code: 您的代码有几个问题:

  • The only thing int[] numbers shares with String[] num input is length . int[] numbersString[] num输入唯一共享的是length All items of the array remain zero, which in itself is sufficient to explain zero result 数组的所有项目保持为零,其本身足以解释零结果
  • Even though avg is double , tot/l is an int . 即使avgdoubletot/l也是int It could be truncated down to zero, depending on the values inside num . 可以将其截断为零,具体取决于num的值。

You need to modify your code to parse String s from num , and compute total as double . 您需要修改代码以从num解析String ,然后将total计算为double After that the division would return the correct result. 之后,除法将返回正确的结果。

Further, you can avoid multiple parses of strings if you return int[] from getdata() method. 此外,如果从getdata()方法返回int[] ,则可以避免多个字符串解析。 Given the small number of inputs, this one is not critical for performance of your code. 由于输入的数量很少,因此这对于代码的性能并不是至关重要的。

You never copy the values from String[] num to your int[] numbers , so when you loop through the whole array numbers , you are going to be summing the default value 0 , l times. 您永远不会将值从String[] num复制到int[] numbers ,因此,当您遍历整个数组numbers ,您将对默认值0 l次累加。

You need to use parseInt() on all the values in num to convert it to ints and store them in numbers , then make sure you do float(tot)/l to cast it to a float during the division. 您需要对num所有值使用parseInt()将其转换为int并将它们存储为numbers ,然后确保在除法过程中执行float(tot)/l将其转换为float。 This avoids truncation due to integer division. 这样可以避免由于整数除法而导致截断。

In the average method you create an empty array called numbers. 在平均值方法中,创建一个称为数字的空数组。 You're calculating the average based on that array which is empty. 您正在基于该为空的数组计算平均值。

Hope this helps 希望这可以帮助

Your numbers array is wrong in the average function. 您的数字数组在平均值函数中是错误的。 Please find the corrected code below, 请在下面找到更正的代码,

double average(String[] num)
        {
            double avg;
            int tot=0;
            int l=num.length;
            for(int j=0;j<l;j++)
            {
                tot=tot+Integer.parseInt(num[j]);
            }
            avg=tot/l;
            return avg;
        }

Change the data types as you need. 根据需要更改数据类型。

I'd recommend printing a from getdata() to ensure that your numbers are getting entered correctly. 我建议从getdata()打印a ,以确保正确输入您的数字。 My best guess is taht something in the split command is not working right. 我最好的猜测是,split命令中的某些内容无法正常工作。

Your problem is your average function. 您的问题是平均功能。 You initializes the array of int[] num , but you did not write the int value in it. 您初始化了int[] num数组,但没有在其中写入int值。 You can do that as in the same way as in void results(String[] arr,double avg) . 您可以像在void results(String[] arr,double avg)

Another problem is, that you get the average avg = tot/l; 另一个问题是平均avg = tot/l; where tot and l are int values. 其中tot和l是int值。 When you divide 2 integer values the result is an int too and the int value will be written into 'avg'. 当您将2个整数值相除时,结果也为int ,并且int值将被写入“ avg”。 If the average is a floiting point number (example input "1 2", then the floiting part get cutoff and your programm returns the avg = 1. Therefore the division needs at least one variable, which is double. 如果平均值是浮点数(示例输入“ 1 2”),则浮起部分将被截断,并且程序将返回avg =1。因此,除法运算需要至少一个变量,该变量为double。

This one should work: 这应该工作:

    double average(String[] num)
    {
        double avg;
        double tot=0;
        int l=num.length;
        for(int j=0;j<l;j++)
        {
            tot=tot+Integer.parseInt(num[j]);
        }
        avg= tot/l;
        return avg;
    }

In your code you are not initializing the numbers[] array . 在您的代码中,您没有初始化number [] array。

double average(String[] num)
     {
         double avg;
         double tot=0;
         int[] numbers = new int[num.length];
         for(int i=0;i<num.length;i++)
         {
             numbers[i]=Integer.parseInt(num[i]);
         }
         int l=num.length;
         for(int j=0;j<l;j++)
         {
             tot=tot+numbers[j];
         }
         avg=tot/l;
         return avg;
     }

If you are using > Jdk8 . 如果您使用的是> Jdk8。 you can use 您可以使用

double average(String[] num) {
        OptionalDouble tot = Arrays.stream(num).mapToInt(s -> Integer.parseInt(s)).average();
        return tot.orElse(0.0);
    }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM