A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 骄傲的倔强 中级黑马   /  2014-1-14 11:38  /  914 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 骄傲的倔强 于 2014-1-15 09:31 编辑
  1. int arr[] = {5,1,6,4,2,8,9};
  2.                 int max = 0;
  3.                 for(int x = 1;x<arr.length;x++)
  4.                         {
  5.                         if (arr[x]>arr[max])
  6.                         {
  7.                                 x = max;
  8.                         }        
  9.                 }
  10.                         System.out.println(arr[max]);
复制代码


为什么得不到数据,哪里出错了。

6 个回复

倒序浏览
代码如下:
  1. public class Demo {
  2.         public static void main(String[] args){
  3.                 int arr[]={3,4,6,7,1};
  4.                 System.out.println(getMax(arr));
  5.         }
  6.         public static int getMax(int arr[])
  7.         {
  8.                 int max=arr[0];
  9.                 for (int x=1;x<arr.length ;x++ )
  10.                 {
  11.                         if(arr[x]>max)
  12.                                 max=arr[x];
  13.                 }
  14.                 return max;
  15.         }
  16. }
复制代码
回复 使用道具 举报
哥们。 你for循环中的  x = max 。 不是错了么。。
你用max 来记录符合条件的数值哦。。

把“ x = max”
修改成 max = x;
就成了
回复 使用道具 举报
  1. public class yy {
  2.         public static void main(String[] args){
  3.                 int arr[]={3,4,6,7,1,9,5};
  4.                 getMax(arr);
  5.         }
  6.         public static void getMax(int arr[])
  7.         {
  8.         int max = 0;
  9.         for(int x = 1;x<arr.length;x++)
  10.                 {
  11.                 if (arr[x]>arr[max])
  12.                 {
  13.                       [color=Red] max=x[/color];//这里的位置写错了你
  14.                 }        
  15.         }
  16.                 System.out.println(arr[max]);
  17. }
  18. }
复制代码
回复 使用道具 举报
app297 发表于 2014-1-14 12:08
哥们。 你for循环中的  x = max 。 不是错了么。。
你用max 来记录符合条件的数值哦。。

马虎了,应该把x的值赋给max的。  谢谢解答
回复 使用道具 举报
本帖最后由 姜胜凯 于 2014-1-14 15:05 编辑

x=max 赋值问题,你应该把x赋值给max...max=x.
回复 使用道具 举报
楼上正解
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马