如何在阵列中找到模式? [英] How can i find the mode in an array?

查看:91
本文介绍了如何在阵列中找到模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Basic它的程序从用户输入6个数字,将它们存储在一个数组中,计算它们的均值和模式。还要计算有多少数字大于均值。
我的程序代码是我错的地方

Basic its this program takes input 6 numbers from user, store them in an Array, calculate their Mean and Mode. Also count how many numbers are greater than mean. The code of my program is where i'm wrong

我的意思是正确但我的模式有问题。

My mean is correct but i have problem in mode.

package p18;

package p18;

import java.util.Arrays;
import java.util.Scanner;

import java.util.Arrays; import 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;
  }}


推荐答案

你没有存储完全输入数组。您需要添加以下内容来存储用户输入:

You are not storing the input into the array at all. You need to add something like the following to store the user input:

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

我还将平均值和总数更改为双倍数,以便您可以获得均值的十进制值,否则它会向下舍入。

I also changed the mean and total to doubles so that you can get a decimal value for the mean, otherwise it would round down.

这篇关于如何在阵列中找到模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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