编写一个C#程序,要求从键盘输入10个数存放在数组中,分别求出最大数和最小数存放在第一第二个元素里
程序一(在主函数中实现):
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication7 { class Program { static void Main(string[] args) { int[] a = new int[10]; for (int i = 0; i < a.Length; i++) a[i] = int.Parse(Console.ReadLine()); for (int i = 0; i < a.Length; i++) { if (a[0] < a[i]) a[0] = a[i]; if (a[0] > a[i]) a[1] = a[i]; } Console.WriteLine("最大值是:{0}", a[0]); Console.WriteLine("最小值是:{0}", a[1]); } } }
程序二(调用其他函数):
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication7 { class Program { public void qiujizhi() { int[] a = new int[10]; for (int i = 0; i < a.Length; i++) a[i] = int.Parse(Console.ReadLine()); for (int i = 0; i < a.Length; i++) { if (a[0] < a[i]) a[0] = a[i]; if (a[0] > a[i]) a[1] = a[i]; } Console.WriteLine("最大值是:{0}", a[0]); Console.WriteLine("最小值是:{0}", a[1]); } static void Main(string[] args) { Program r = new Program(); r.qiujizhi(); } } }
两段代码结果均如下图:
两段代码不同之处在于,程序二声明调用了其他成员函数,可以让程序看起来一目了然,不容易出错。
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。