Java的:在阵列中找到的最高值 [英] Java: Finding the highest value in an array

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

问题描述

有关某种原因,这code是阵列中的最高值打印三个值,当我试图打印只有一个(也就是11.3)。它为什么这样对我可有人请解释一下吗?

感谢。

 进口java.util.Scanner中;公共类Slide24
{
    公共静态无效的主要(字串[] args)
    {
        扫描仪在=新的扫描仪(System.in);        双[] = decMax -2.8 {,-8.8,2.3,7.9,4.1,-1.4,11.3,10.4,
            8.9,8.1,5.8,5.9,7.8,4.9,5.7,-0.9,-0.4,7.3,8.3,6.5,9.2,
            3.5,3,1.1,6.5,5.1,-1.2,-5.1,2,5.2,2.1};        双总= 0,avgMax = 0;        对于(INT计数器= 0;反< decMax.length;反++)
        {
         总+ = decMax [窗口];
        }        avgMax =总/ decMax.length;        System.out.printf(%s%2.2F \\ n,十二月的平均最高气温为:avgMax);        //查找最高值
        双最大= decMax [0];        对于(INT计数器= 1;计数器< decMax.length;反++)
        {
         如果(decMax [计数器]>最大)
         {
          最大= decMax [窗口];
          的System.out.println(为十二月最高的最大值是:+最大);
         }        }
    }
}


解决方案

它的每找到一个比当前的最大较高时打印出一个数字(这发生在你的情况发生了三次。)以外的移动打印for循环,你应该是不错的。

 的for(int柜台= 1;计数器< decMax.length;反++)
{
     如果(decMax [计数器]>最大)
     {
      最大= decMax [窗口];
     }
}的System.out.println(为十二月最高的最大值是:+最大);

For some reason this code is printing three values for the highest value in the array when I'm trying to print just one (which is 11.3). Can someone please explain to me why it is doing this?

Thanks.

import java.util.Scanner;

public class Slide24
{
    public static void main (String [] args)
    {
        Scanner in = new Scanner(System.in);

        double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
            8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
            3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};

        double total = 0, avgMax = 0;

        for (int counter = 0; counter < decMax.length; counter++)
        {
         total += decMax[counter];
        }

        avgMax = total / decMax.length;

        System.out.printf("%s %2.2f\n", "The average maximum temperature for December was: ", avgMax);

        //finds the highest value
        double max = decMax[0];

        for (int counter = 1; counter < decMax.length; counter++)
        {
         if (decMax[counter] > max)
         {
          max = decMax[counter];
          System.out.println("The highest maximum for the December is: " + max);
         }

        }        
    }
}

解决方案

It's printing out a number every time it finds one that is higher than the current max (which happens to occur three times in your case.) Move the print outside of the for loop and you should be good.

for (int counter = 1; counter < decMax.length; counter++)
{
     if (decMax[counter] > max)
     {
      max = decMax[counter];
     }
}

System.out.println("The highest maximum for the December is: " + max);

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

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