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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容