An elegant way to add or subtract a fixed value based on input

Take it easy with me for a moment.

I have a method that should add or subtract a fixed value depending on the given input.

I know my maximum value 1.0f, minimum value 0.0f. Fixed value 0.1f.

Now, if the input value 1.0f, the method should subtract until the value is there 0f. If the input value 0f, the method should add 0.1funtil the value is there 1.0f.

So the working method for 0fto 1fwill be:

void Foo(float input) {
    float step = .1f;
    for (float i=0f; i<=1f; i += step) {
        input = i;
    }
}

Obviously, I can have an if-statement checking the input value, but is there any other way to achieve this within the framework of one method? I feel that the basic arithmetic operation is simply missing here.

+4
source share
2 answers

just an offer

I think that the step can be configured as positive or negative, based on the initial value, and use the do-while command, so it runs for the first time until it reaches the final value.

Based on your code

void Foo(float input) {
    float step = input == 0f ? .1f : -0.1f;

    do 
    {
        input = input + step
    } while (input > 0f && input < 1.0f);
}
+5
source

if , . , , , .

void foo(float input)
{
    float step = (.5f - input)/5.f;
    do 
    {
        input += step;
    } while (input > 0.0f && input < 1.0f);
}

foo(1.0f) --> -7.45058e-08
foo(0.0f) --> 1
0

Source: https://habr.com/ru/post/1656914/


All Articles