如何获得c#中的最大值

时间:2013-10-05 00:38:23

标签: c#

我有这个非常简单的C#代码:

static void Main(string[] args)
{
    int i, pcm, maxm = 0;
    for (i = 1; i <= 3; i++)
    {
        Console.WriteLine("Please enter your computer marks");
        pcm = int.Parse(Console.ReadLine());
    }
    Console.ReadKey();
}

我想获得var pcm的最大值,我怎么能这样做?

5 个答案:

答案 0 :(得分:4)

跟踪它!

对于每次迭代,如果输入的数字大于maxm中的数字,则将maxm设置为等于当前输入的数字。

最后,你将获得最大值。

伪代码:

max = 0
for three iterations
  get a number
  if that number is more than max
    then set max = that number

答案 1 :(得分:0)

只是张贴的替代品。

static void Main(string[] args)
{
   var numbers = new List<int>();

   for (var i = 1; i <= 3; i++)
   {
       Console.WriteLine("Please enter your computer marks");
       numbers.Add(int.Parse(Console.ReadLine()));
   }

   Console.WriteLine(string.Format("Maximum value: {0}", numbers.Max());
   Console.ReadKey();
}

答案 2 :(得分:0)

您可以在maxm变量中保存输入的值。如果用户键入较大的数字,则替换该值:

static void Main(string[] args)
{
    int i, pcm = 0, maxm = 0;
    for (i = 1; i <= 3; i++)
    {
        Console.WriteLine("Please enter your computer marks");
        pcm = int.Parse(Console.ReadLine());

        // logic to save off the larger of the two (maxm or pcm)
        maxm = maxm > pcm ? maxm : pcm;
    }
    Console.WriteLine(string.Format("The max value is: {0}", maxm));
    Console.ReadKey();
}

答案 3 :(得分:0)

我会尝试这个

static void Main(string[] args)
{
    int i, pcm, maxm = 0;
    for (i = 1; i <= 3; i++)
    {
        Console.WriteLine("Please enter your computer marks");
        pcm = int.Parse(Console.ReadLine());
        if(maxm <= pcm)
        {
             maxm = pcm;
        }
    }
    Console.ReadKey();
}

答案 4 :(得分:0)

只是为了好玩,这是另一个使用Linq的解决方案。

static void Main(string[] args)
{
    int i, pcm, maxm = 0;
    List<int> vals = new List<int>();
    for (i = 1; i <= 3; i++)
    {
    Console.WriteLine("Please enter your computer marks");
    pcm = int.Parse(Console.ReadLine());
    vals.Add(pcm);
    }
    maxm = vals.Max(a => a);
    Console.ReadKey();
}