Search code examples
roundingmodulofloor

How to write a RoundDown() function with loops, + - * / and % (modulo)?


I was just thinking, if you only had loops, + - * / and % (modulo). Would it be possible to round a float number down to the next integer?
For example 278.791 to 278?

I've been thinking about that for a long time now, but still couldn't find a solution. Is it even possible?


Solution

  • In Python % works:

    #!/usr/bin/python
    x = 278.791
    y = x - (x % 1)
    print x, y
    

    In C other methods must be used:

    #include <stdio.h>
    #include <math.h>
    int main() {
        float x = 278.791;
        float y = fmod(x,1.0);
        printf("%f, %f\n", x, y);
        x = 278.791;
        y = x - (int)x;
        printf("%f, %f\n", x, y);
    }