Pregunta

Yes I would like to know if there is a way to convert this logic, into a more mathfriendly solution. For one, I would like to learn a bit more math, two I am curious about if it is possible.

edit Yes yes, some of the lines are redundant, or not typesafe etc etc, can we please stick to the question at hand people? :)

The goal is to round down each quarter to it's previous quarter if not above it.

Example:

0.25 = 0, 0.27 = 0.25, 0.50 = 0.25, 0.52 = 0.50, 0.75 = 0.50, 0.78 = 0.75

float lulzRound(float value)
{
    int integer = (int)value;
    float start = value - (float)integer;
    float result;
    if(start < 0.25)
    {
        result = 0;
    }
    else if((start > 0.25) && (start <= 0.50))
    {
        result = 0.25;
    }
    else if((start > 0.50) && (start <= 0.75))
    {
        result = 0.50;
    }
    else if((start > 0.75) && (start < 1))
    {
        result = 0.75;
    }
    return (float)integer + result;
}
¿Fue útil?

Solución

One way to do that would be this:

return floor(value*4.0)*0.25;

This translates a value of 0.25 into 0.25. If you need to translate it into 0.0, use this:

return ceil(value*4.0)*0.25-0.25;

But be aware that this will also translate 0.0 into -0.25. If that's not acceptable, you could use this:

return value < 0.25 ? 0 : ceil(value*4.0)*0.25-0.25;

Or another alternative:

return ceil(value*4.0)*0.25 - (fmod(value,1) ? 0.25 : 0);

Here's a short test program:

#include <iostream>
#include <cmath>

float round(float value)
{
    return ceil(value*4.0)*0.25 - 0.25;
}
int main()
{
    for (float i=0.0; i < 1.5; i+=0.05)
        std::cout << i << " ==> " << round(i) << '\n';
}

Otros consejos

float lulzRound(float value) {
    value *= 4.0f;
    int i = static_cast<int>(value);
    if(i > 0 && value == static_cast<float>(i)) {
        i--;
    }
    return static_cast<float>(i)*0.25f;
}

This code works for value >= 0 as you specified. For negative numbers it does something similar.

It looks like you want to round to units of one-quarter. Something like this:

int(value * 4) / 4.0     // [0.00, 0.25) -> 0.00
                         // [0.25, 0.50) -> 0.25
                         // [0.50, 0.75) -> 0.75
                         // [0.75, 1.00) -> 0.75

Or this:

int(value * 4 - 1) / 4.0 // [0.00, 0.25) -> -.25
                         // [0.25, 0.50) -> 0.00
                         // [0.50, 0.75) -> 0.25
                         // [0.75, 1.00) -> 0.50
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top