它的程序基本从用户那里输入6个数字,将它们存储在一个数组中,计算它们的均值和众数。还计算多少个数字大于平均值。我程序的代码是我错的地方
我的意思是正确的,但是我在模式上有问题。
包p18;
导入java.util.Arrays; 导入java.util.Scanner;
public class P18 { public static void main(String[] args) { Scanner S=new Scanner(System.in); int[] arr1=new int [6]; for (int i = 0; i < 6; ++i) { int g = S.nextInt(); arr1[i] = g; } int input=6; double total=0d; double mean; for(int i=0;i<input;i++) { total=total+arr1[i]; } mean= total/input; System.out.println("the mean is:" + mean);
PROBLEM STARTS FROM HERE MODE PORTION int max=0;//problem starts from here int maxFreq=0; Arrays.sort(arr1); max = arr1[arr1.length-1]; int[] count = new int[max + 1]; for (int i = 0; i < arr1.length; i++) { count[arr1[i]]++; } for (int i = 0; i < count.length; i++) { if (count[i] > maxFreq) { maxFreq = count[i]; } } for (int i = 0; i < count.length; i++) { if (count[i] == maxFreq) { return i; }} return -1; }}
您根本没有将输入存储到数组中。您需要添加类似以下内容的内容来存储用户输入:
Scanner S=new Scanner(System.in); int[] arr1=new int [6]; for (int i = 0; i < 6; ++i) { int g = S.nextInt(); arr1[i] = g; } int input=6; double total=0d; double mean; for(int i=0;i<input;i++) { total=total+arr1[i]; } mean= total/input; System.out.println("the mean is:" + mean);
我还将平均值和总数更改为双精度,以便您可以获取平均值的十进制值,否则将四舍五入。