当前位置: 首页 > 编程语言 > C#

如何求最大数和最小数C#分享

时间:2023-04-10 20:08:26 C#

C#如何求最大数和最小数我从三个变量中得到三个值。我如何检查谁是最高数字,谁是最低数字?数字表示如下:privateint_score1;私人int_score2;私人int_score2;代码:publicintHighest{此处返回最高数;}publicintLowest{返回最小值;}我可以计算构造函数中最高和最低的数字吗?强制性Linq答案:PublicintHighest(paramsint[]inputs){returninputs.Max();}publicintLowest(paramsint[]inputs){returninputs.Min();这样做的好处是它可以接受任意数量的整数输入。为了使其故障安全,您应该检查空/空输入数组(意味着没有任何内容传递给该方法)。要在没有Linq的情况下执行此操作,您基本上只需要模仿扩展方法执行的逻辑:PublicintLowest(paramsint[]inputs){intlowest=inputs[0];foreach(varinputininputs)if(input同样,为了确保万无一失,您应该检查一个空的或空的输入数组,因为调用Lowest()将抛出ArrayIndexOutOfBoundsException。这是一种方法:publicintHighest{get{returnMath.Max(_score1,Math.Max(_score2,_score3));}}publicintLowest{get{returnMath.Min(_score1,Math.Min(_score2,_score3));}}int[]numbers=new[]{_score1,_score2,_score3};intmin=numbers.Min();intmax=numbers.Max();最高回报(x>y)?(x>z?x:z):(y>z?y:z)返回(x>y)?(x>z?x:z):(y>z?y:z)最小回报(xreturn(x如果你想简单地检查哪个是最高的,你可以这样做privateint_highest=_score1;if(_score2>_highest)_highest=_score2if(_score3>_highest)_highest=_score3同样你可以找到最低的privateint_lowest=_score1;if(_score2这是你可以做的事情:publicclassNumbers{privateint_number1;privateint_number2;privateint_number3;publicreadonlyintHighest;publicreadonlyintLowest;publicNumbers(intnum1,intnum2,intnum3){inthigh;intlow;_number1=num1;_number2=num2;_number3=num3;high=num1>num2?num1:num2;high=high>num3?high:num3;low=num1使用LINQ-to-Objects,你可以做这样的事情varnumbers=new[]{_score1,_score2,_score3};数字.排序();varlowest=numbers.First();varhighest=数字。最后的();仅供参考:在某些情况下,您将拥有三个以上的变量(可能不知道有多少)。如果它们存储在数组中,请执行以下操作:intHighest(int[]numbers){inthighest=Int32.MinValue();for(inti=0;ihighest)highest=numbers[i];}返回最高;}intLowest(int[]numbers){intlowest=Int32.MaxValue();for(inti=0;i这适用于任何长度的int数组。使用系统找到最大和最小的数字;命名空间LargeSmall;{类程序{publicstaticvoidMain(){floatlarge,small;int[]a=newint[50];Console.WriteLine("请输入数组的大小");intmax=Convert.ToInt32(Console.ReadLine());Console.WriteLine("请输入数组元素");for(inti=0;ilarge)large=a[i];elseif(a[i]这是一个简单的逻辑求最小数的输入:11,0,3,33输出:“0”以上就是C#学习教程的全部内容:如何求最大和最小numberC#分享,如果对大家有用,还需要了解更多C#学习教程,希望大家多多关注---namespacePurushLogics{classPurush_SmallestNumber{staticvoidMain(){intcount=0;Console.WriteLine("EnterTotalNumberofIntegersn");count=int.Parse(Console.ReadLine());int[]numbers=newint[count];Console.WriteLine("Enterthenumbers");//输入44,55,111,2Output="2"for(inttemp=0;tempnumbers[small]){smallest=numbers[small];}}Console.WriteLine("SmallestNumberis:"{0}"",smallest);Console.ReadKey();}}}网络采集不代表站着如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: