//建立一个静态方法,用于找出一个int数组中最大的值,并传递出来数组个数的参。
static int MaxValue(int[] intArray, out int maxIndex)
{
int maxVal = intArray[0];//取得数组里第一个值。
maxIndex = 0;
//循环数组,用数组中以第2个元素开始与maxVal 比较,如果maxVal 小,就把大的值赋给maxVal ,然后把数组当前的遍历到得元素在数组中的序号赋给maxIndex 。
for (int i = 1; i < intArray.Length; i++)
{
if (intArray[i] > maxVal)
{ maxVal = intArray[i];
maxIndex = i;
}
}
return maxVal;//返回最大的值。
}
static void Main(string[] args)
{
int[] myArray ={ 1, 3, 2, 5, 7, 4, 0 };
int maxIndex;//定义一个int类型的变量,因为MaxValue ()方法有out参数,所以必须先定义一个变量,供方法使用。MaxValue()方法中必须赋值给这个变量,等方法结束后,这里定义的这个变量就会带有MaxValue ()方法中赋给的值了。
Console.WriteLine("The maximun value in myArray is {0}",MaxValue (myArray ,out maxIndex ));
//在屏幕上显示一行:The maximun value in myArray is 7
{0}在这里是后面调用MaxValue (myArray ,out maxIndex )方法而取得的返回值。同时,也会把
maxIndex 赋上值,值为MaxValue()方法中的maxIndex。
Console.WriteLine("The first occurrence of this value is at element {0}",maxIndex +1);
//在屏幕上显示一行:first occurrence of this value is at element 7
因为位置是从0开始,所以要把数组中最后一位的序号加上1才是数组中元素的个数。
Console.ReadKey();//等待键盘输入才退出程序。为了使调试时看到输出结果。 如果没有此句,命令窗口会一闪而过。
}
}
}
说的这么详细,楼主给分吧!!!
这段代码 是求一个数组中的最大值 及最大值位置
maxIndex 用来存储最大值的位置 只所有这儿用out 输出参数是因为 一个函数只能返回一个值 既然返回了最大值就不能再用return 返回最大值位置,所以就用了out 参数
return maxVal 这个是函数返回值 函数返回必定是返回调用他的位置
也就是这儿 Console.WriteLine("The maximun value in myArray is {0}",MaxValue (myArray ,out maxIndex ));
这块其实应该是分两步 一是调用函数取得值 二是输出 这儿可以分开写的
调用函数他是写在了输出里面 你初学不明白的话可以分开写
int nTmp=MaxValue (myArray ,out maxIndex );
Console.WriteLine("The maximun value in myArray is {0}",nTmp);
问题1:输出的是这个数组中最大的一个数。和这个数在这个数组中是第几个。
问题2:写int maxIndex原因是因为在定义MaxValue方法的时候有一个参数是加了out标识的。加了这个在调用这个方法的地方就必须先定义一个这个变量。
问题3:这里返回的值会Console.WriteLine("The maximun value in myArray is {0}",MaxValue (myArray ,out maxIndex ));这里输出,就是在调用MaxValue方法的时候会返回这个值。
问题4:有调用,在Console.WriteLine("The maximun value in myArray is {0}",MaxValue (myArray ,out maxIndex ));
里调用了。
问题1:这段代码是输出参数的内容,但是我看不出这个代码想表达的意思,请略加详细地解释下关键的几句代码所表达的含义(这是我想问的重点!!!)
答:上面的函数是取数组中最大值的索引值。
问题2:在Main()函数中,的int maxIndex;这句代码在这里的用途是什么?
答:定义变量名为maxIndex,int型。
问题3:return maxVal;这里要返回的值会返回到哪里(具体点,谢谢!)
答:调用函数后输出值。
问题4:这里用到了函数的调用吗?(即:有没有调用函数MaxValue(),有的话,请指明那句代码!)
答:这里调用了函数Console.WriteLine("The maximun value in myArray is {0}",MaxValue (myArray ,out maxIndex ));
MaxValue (myArray ,out maxIndex )
传入参数myArray和maxIndex
static int MaxValue(int[] intArray, out int maxIndex)
{
int maxVal = intArray[0];
maxIndex = 0;
for (int i = 1; i < intArray.Length; i++)
{
if (intArray[i] > maxVal)
{ maxVal = intArray[i];
maxIndex = i;
}
}
return maxVal;
}
static void Main(string[] args)
{
int[] myArray ={ 1, 3, 2, 5, 7, 4, 0 };
int maxIndex;
Console.WriteLine("The maximun value in myArray is {0}",MaxValue (myArray ,out maxIndex )); //问题4:此处调用函数MaxValue().
Console.WriteLine("The first occurrence of this value is at element {0}",maxIndex +1);
Console.ReadKey();
}
}
}
问题1:获得数列里的最大值,并得到这个值在数列中的位置。
问题2: int maxIndex; //定义一个整型变量.
问题3: int ivalue; ivalue= MaxValue (myArray ,out maxIndex )// return maxVal返回给这里的ivalue.