練習8:計算字串的個數
1
2
string s = "asdfsf";
Console.WriteLine(s.Length);
練習9:用方法實現:計算最大值
思考:方法的參數?返回值?擴展(*)
計算任意多個數之間的最大值(提示:params)
傳入兩個參數(計算兩個數的最大值)
1
2
3
4
5
Console.WriteLine(GetMax(100,99));
static int GetMax(int n1, int n2)
{
return n1 > n2 ? n1 : n2;
}
傳入陣列
1
2
3
4
5
6
7
8
9
10
11
12
13
int[] nums = { 1, 2, 4, 5, 9 };
int max = GetMax(nums);
Console.WriteLine(max);
static int GetMax(int[] nums)
{
int max = nums[0]; //先給一個假定值
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] > max) max = nums[i];
}
return max;
}
params參數方法
params可變動參數,把實參列表中,每一個數字都當作是陣列中的元素。
params可變參數,必須是形參列表最後一個參數
填參數值的時候,可以有兩個選擇:
- 放陣列進去
GetMax(nums); - 放元素進去
GetMax(1, 2, 3, 4, 5);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//放陣列進去
//int[] nums = { 1, 2, 4, 5, 9 };
//int max = GetMax(nums);
//放元素進去
int max = GetMax(1, 2, 3, 4, 5);
Console.WriteLine(max);
static int GetMax(params int[] nums)
{
int max = nums[0]; //先給一個假定值
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] > max) max = nums[i];
}
return max;
}