C# 如何从变量中获取最大和最小数值(两者)

C# How to get the Max and Min numerical values (both) from a variable

我有一个C#代码,下一个情况

2 个变量:double qty1double qty2 经常收到 2 个不同的 positive/negative 号码。

然后有一个变量double currentResult 它接收 qty1 和 qty2 的总和(positive/negative 个数字)并且 currentResult 在每次 qty1 或 qty2 接收到新数量时改变它的值。 currentResult 的值未存储在任何地方,不需要它,因为 currentResult 仅用于显示目的,因此它仅显示在屏幕中,作为实际信息显示并完成。直到现在我们都在谈论显示一个简单的总和结果,所以请不要把你的答案集中在这部分,因为这不是重要的部分。

好的,我需要的是从 currentResult 获取 2 个值,随着新数据来自 qty1 and/or qty2:

我们随便举一个例子例子:当程序启动时,假设currentResult显示的第一个结果是7,然后是-1,然后是3,然后是-8,然后是10 , 然后 -4, -11, 15... 并且它在接收到新数据时不断更新它的当前值,然后:

- I need **maxResult** first displays as its value the number 7, then the number 10 as new max number among all currentResult has had until now, then 15, and so on.

- I need **minResult** first displays as its value the number -1, then the number -8 as new min number among all currentResult has had until now, then -11 and so on.

稍后,也许我可能需要存储 maxResult/minResult 的最后 5 个或 n 个值之类的东西,但现在,我主要需要的是要保留的当前(最后)Max/Min 个值在屏幕上可见,直到到达任何新的 Max/Min 号码。

这里我用“显示”这个词来直观地理解我需要什么作为最终结果,但是我主要需要的是获得maxResult和minResult的必要代码,因为我没有'如此处所述,我找不到从变量中获取这 2 个值的方法。

请注意这里我们不是在谈论一个预定义的数字列表,我们需要在其中找到最大和最小数字,不,这里我们需要基于单个变量值的结果 (currentResult ), 随着时间的推移处理它所具有的数值。

您可以使用 Math.Max(double) 和 Math.Min(double) 函数来计算值。

例如:

using System;

namespace YourApp
{
    class MaxMin
    {
        public double maxResult = Double.MinValue;
        public double minResult = Double.MaxValue;

        public void update(double currentResult)
        {
            maxResult = Math.Max(maxResult, currentResult);
            minResult = Math.Min(minResult, currentResult);
        }
    }
}

您可以创建一个 MaxMin 对象并在对 currentResult 进行新赋值时调用其 update() 方法,并从 maxResult 和 minResult 成员中获取值。

如果您不想要对象的开销,或者在更新 currentResult 的地方没有方便的地方访问它,则将变量和方法设为静态。

using System;
public class Program
{     
    static Random random = new Random();
    public static void Main()
    {       
        double maxResult = 0;
        double minResult = 0;
    
        for( var i = 0;i<5;i++)
        {
            double currentResult = GetCurrentResult();
    
            maxResult = Math.Max(maxResult, currentResult);
            minResult = Math.Min(minResult, currentResult);
            Console.WriteLine("Curent Result " + currentResult);
            Console.WriteLine("Max Result " + maxResult);
            Console.WriteLine("Min Result " + minResult);
        }
    }

    private static double GetCurrentResult()
    {
        double maxValue = 100d;
        double minValue = -100d;
        double sample = random.NextDouble();
        return (maxValue * sample) + (minValue * (1d - sample));
    }   
}