我找不到获取数组中最大数字的方法(Ar.getMax())。我的输出一直为0

我试图使用函数 getMax() 获取数组中的最大数字,但输出始终为 0。


当输入为: 12 87 3 10 55 69 40

结果应为: 69

相反结果为: 0


  public int getMax()

      {

          int x=1;

          int y=0;   


          for(int i=0; i<size; i++)

              {

                  if(i!=size-1)

                  {

                      if(arr[i]>arr[x])

                      {

                          y=arr[i];

                          x++;

                      }

                  }

              }

          return y;

      }


蝴蝶不菲
浏览 118回答 3
3回答

幕布斯6054654

由于 89 较大,我认为您需要数组中最长非递减子序列的局部最大值。这个问题没有很好地表述,所以可能没有作业。array: 12 87 3 10 55 69 40sequences: 12 87&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3 10 55 *69* answer&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;40int maxOfLongestSubsequence(int[] a) {&nbsp; &nbsp;int maxSeqLength = 0;&nbsp; &nbsp;int max = Integer.MIN_VALUE;&nbsp; &nbsp;int seqStart = -1;&nbsp; &nbsp;for (int i = 0; i <= a.length; ++i) {&nbsp; &nbsp; &nbsp; &nbsp;if (i == 0 || i == a.length - 1 || a[i] < a[i - 1]) { // New subsequence&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int seqLength = i - seqStart;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (i - seqLength > maxSeqLength) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;maxSeqLength = seqLength;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;max = a[i - 1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;seqStart = i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return max;}阐述问题。像我一样描述数据。并将其编程出来。

德玛西亚99

只需将默认最大值设置为数组中的第一个值即可。然后,迭代数组,将该值与数组中的下一个值进行比较。如果较大,则将其分配给 max。继续到数组末尾。

料青山看我应如是

您可以像这样选择 int 数组的最大值:int [] numbers = new int[]{12,87,3,10,55,69,40};&nbsp; &nbsp; &nbsp; &nbsp; int max = numbers[0];&nbsp; &nbsp; &nbsp; &nbsp; for(int current : numbers) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max = current >= max ? current : max;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(max);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java