I have a loop that repeats itself 100 times and every time it generates a number from 34.5 to 42.0
Random rnd = new Random();
const double MAX = 42.0;
const double MIN = 34.5;
//Console.WriteLine("{0:f1}",num);
for (int i = 0; i < 100; i )
{
double num = rnd.NextDouble() * (MAX - MIN) MIN;
Console.WriteLine("{0:f1}", num);
}
and I want to find the highest number and print it but I don't know how to find the number
CodePudding user response:
You can store your values to a List and then find the max and min values
Random rnd = new Random();
const double MAX = 42.0;
const double MIN = 34.5;
//Console.WriteLine("{0:f1}",num);
List<double> lst = new List<double>(100);
for (int i = 0; i < 100; i )
{
double num = rnd.NextDouble() * (MAX - MIN) MIN;
lst.Add(num);
Console.WriteLine("{0:f1}", num);
}
Console.WriteLine("max number is " lst.Max().ToString());
CodePudding user response:
Here's the simplest change to your existing code:
Random rnd = new Random();
const double MAX = 42.0;
const double MIN = 34.5;
//Console.WriteLine("{0:f1}",num);
double max = double.MinValue;
for (int i = 0; i < 100; i )
{
double num = rnd.NextDouble() * (MAX - MIN) MIN;
max = num > max ? num : max;
}
Console.WriteLine("{0:f1}", max);
CodePudding user response:
Create a variable outside the loop, and then set that to the minimum possible value. Then on each iteration, if the generated number is larger than that, store the generated number. Then after the loop you can print it out.
Random rnd = new Random();
const double MAX = 42.0;
const double MIN = 34.5;
double highestRandom = MIN;
//Console.WriteLine("{0:f1}",num);
for (int i = 0; i < 100; i )
{
double num = rnd.NextDouble() * (MAX - MIN) MIN;
if (num > highestRandom)
{
highestRandom = num;
}
Console.WriteLine("{0:f1}", num);
}
Console.WriteLine("The highest number was: {0:f1}", highestRandom);