Home > Software engineering >  C#/Xamarin Save max read value of Variable
C#/Xamarin Save max read value of Variable

Time:01-19

I'm continually writing values to a variable and would like a separate variable to keep track of the max value that the first variable reaches. Searches of 'saving variable max value' returns a lot of info about maximum values that variable types can represent as one would expect.

Would like for it to look something like:

while (device == connected)
{
     float x = (float) read.device(1);
     float maxvalue = 0.00;
     if (x > maxvalue)
     {
          maxvalue = max(x); //max() is a function I'd like to implement if one isn't already available
     }
}

Obviously the syntax is not correct in this example but I showed it to get the general idea of what I was looking for.

The value for x is continually changing up to 30 times per second and I only want to keep track of the highest value it has seen since entering the while loop. This seems simple and I feel like I'm missing something...

CodePudding user response:

Move the declaration out of the loop and then 2 choices:

if (x > maxvalue) maxvalue = x; 

or

maxvalue = Math.Max(maxvalue, x);

Now you reset maxvalue to 0.0 in every iteration so every value > 0 becomes maxvalue.

So

float maxvalue = 0.00;
while (device == connected)
{
     float x = (float) read.device(1);     
     maxvalue = Math.Max(maxvalue, x);
}

I recommend using Math.Max always instead of if statement as as it also handles corner cases for floats like NaN.

CodePudding user response:

Here are some alternatives:

float maxvalue = 0.0f;
while (device == connected)
{
    float x = (float)read.device(1);
    if (x > maxvalue)
    {
        maxvalue = x;
    }
}

or:

float maxvalue = 0.0f;
while (device == connected)
{
    float x = (float)read.device(1);
    maxvalue = Math.Max(maxvalue, x);
}

or:

float maxvalue = 0.0f;
while (device == connected)
{
    float x = (float)read.device(1);
    maxvalue = x > maxvalue ? x : maxvalue;
}

or make IEnumerable<float> method:

public IEnumerable<float> DeviceValues()
{
    while (device == connected)
    {
        yield return (float)read.device(1);
    }
}

Then it's just:

float maxvalue = DeviceValues().Max();
  •  Tags:  
  • Related