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

2018-01-03  本文已影响0人  Class_Lee

//第一种

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]);

上一篇下一篇

猜你喜欢

热点阅读