c#取最大值 第二种方法bug:逻辑错误

//第一种

int[] arr = { 1, 1, 3, 5, -6, 4, 9, 9, 2 };

Array.Sort (arr);

Console.WriteLine (arr [6]);

//第二种  错误 当arr数组全为负数时,if不会执行

int[] arr = { 1, 1, 3, 5, 6, 4, 9, 9, 2 };

int temp;

for (int i = 0; i < arr.Length; i++) {

if (arr [i] > temp) {

temp = arr [i];

}

}

Console.WriteLine (temp);

//第三种

int[] newArray = { 1, 3, 5, 6, 4, 9, 2 };

int max = newArray [0];

for (int i = 0; i < newArray.Length; i++) {

//当前保存的值不如刚查到的大

if (max < newArray [i]) {

max = newArray [i];

}

}

Console.WriteLine (max);

//第四种

int[] newArray = { 1, 3, 5, 6, 4, 9, 2 };

for (int i = 0; i < newArray.Length - 1; i++) {

for (int j = 0; j < newArray.Length - i - 1; j++) {

if (newArray [j] > newArray [j + 1]) {

int temp = newArray [j];

newArray [j + 1] = newArray [j];

newArray [j] = temp;

}

}

}

Console.WriteLine (newArray [newArray.Length - 1]);

//第五种

int[] newArray = { 1, 3, 5, 6, 4, 9, 2 };

int maxIndex = 0;

int i = 0;

for (i = 0; i < newArray.Length; i++) {

if (newArray [maxIndex] < newArray [i]) {

maxIndex = i;

}

}

Console.WriteLine (newArray [maxIndex]);

你可能感兴趣的:(c#取最大值 第二种方法bug:逻辑错误)