I have this pretty simple C# code:
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();
}
I would like to get max value for the var pcm, how could I do it?
Just keep track of it!
For each iteration, if the entered number is greater than the number that you have in maxm
, then set maxm
equal to the current entered number.
At the end, you'll have the maximum.
Pseudocode:
max = 0
for three iterations
get a number
if that number is more than max
then set max = that number
Just another alternative to the posted ones.
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();
}
You can save the typed in value in the maxm
variable. If the user types a larger number, then you replace that value:
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();
}
I would try this
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();
}
Just for fun, here's another solution that uses 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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.