简体   繁体   English

找到循环中的最高数字

[英]find the highest number in loop

I have a loop that repeats itself 100 times and every time it generates a number from 34.5 to 42.0我有一个重复 100 次的循环,每次它生成一个从 34.5 到 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我想找到最大的数字并打印出来,但我不知道如何找到这个数字

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());

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);

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);

Try it online在线试用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM