任務描述
本關任務:有一個包含10個元素的數組,從鍵盤輸入n的值,及前n個元素的值,要求:編程實現尋找數組中最小值和最大值。
注意:n的值為不超過10的正整數,否則輸出input error!
如:從鍵盤輸入n的值為10,各元素的值分別為31、94、55、83、67、72、29、12、88、56
則輸出
最大值:94
最小值:12
如何求出最大值、最小值
求數組的最大值,是不是很像打擂台呢?
對於一群人我們不知道誰最厲害,所以我們准備一個擂台,並挑選第一個人為擂主(max),擂台下的人不斷的(循環)來挑戰擂主,如果贏了那挑戰者就是擂主,之前的擂主就下台了,直到沒有挑戰者了,那最后一個擂主就是最厲害的那個了。
求數組的最小值與求最大值類似。
編程要求
根據提示,在右側編輯器補充代碼,計算並輸出數組的最小值和最大值。
測試說明
平台會對你編寫的代碼進行測試:
測試輸入:
5
4
91
51
2
32;
預期輸出:
最大值:91
最小值:2
測試輸入:
6
5
1
151
12
22
100
預期輸出:
最大值:151
最小值:1
開始你的任務吧,祝你成功!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ch705
{
class Program
{
static void Main(string[] args)
{
/******begin*******/
try
{
int n = Convert.ToInt32(Console.ReadLine());
if (n < 0 || n > 10)
{
Console.WriteLine("input error!");
return ;
}
int[] a = new int[n];
for (int i = 0; i < n; ++i)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
int max = -1, min = 1000000;
for(int i = 0; i < n; ++ i)
{
if(a[i] > max) max = a[i];
if(a[i] < min) min = a[i];
}
Console.WriteLine("最大值:{0}", max);
Console.WriteLine("最小值:{0}", min);
}
catch(Exception e)
{
Console.WriteLine("input error!");
}
/*******end********/
}
}
}
