如何在 c# 中获取最大值
本文关键字:获取 最大值 | 更新日期: 2023-09-27 18:33:55
我有这个非常简单的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的最大值,我该怎么做?
只要跟踪它!
对于每次迭代,如果输入的数字大于 maxm
中的数字,则将maxm
设置为等于当前输入的数字。
最后,您将拥有最大值。
伪代码:
max = 0
for three iterations
get a number
if that number is more than max
then set max = that number
您可以将键入的值保存在 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();
}
我会试试这个
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();
}
只是已发布的另一种选择。
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();
}
只是为了好玩,这是另一个使用 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();
}