Round to Next .05 in C

前端 未结 5 1280
梦毁少年i
梦毁少年i 2021-01-27 08:44

Consider a float value like 1.82 set by the user. How do I find the next highest .05 value? For the given example the next highest value is 1.85.

Is the

相关标签:
5条回答
  • 2021-01-27 09:23

    Multiply by 20, use ceiling, divide by 20.

    0 讨论(0)
  • 2021-01-27 09:25
    float fixedCeil(float num, float factor)
    {
      float steps = 1.0f / factor;
      return ceil(steps*num)/steps;
    }
    
    assert(fixedCeil(2.43f, 0.05f) == 2.45f);
    

    (assert is just fictional)

    0 讨论(0)
  • 2021-01-27 09:32

    Code for @Justin's answer. Note that this is very easy to generalize.

    #include <math.h>
    #include <stdio.h>
    
    int main(void) {
        int i;
        double numbers[] = {
            1.82, 0.3, 0.2, 0.5, 10000000000.849,
        };
    
        for (i = 0; i < sizeof(numbers)/sizeof(numbers[0]); ++i) {
            double scaled = ceil(20 * numbers[i]);
            printf("%.2f\n", scaled/20.0);
        }
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-27 09:36

    You can use something like

        // Rounds X to the nearest Y
        double round(double x, double y)
        {
            return floor(x / y + 0.5) * y;
        }
    
    0 讨论(0)
  • 2021-01-27 09:46

    A great useful and informative resource for Rounding methods.

    0 讨论(0)
提交回复
热议问题