首页 > 解决方案 > 如何将整数向下舍入到最接近的数字倍数?

问题描述

我正在尝试将整数四舍五入到最接近的数字倍数。

说数字等于80

有比这更有效的方法x -= (x % the_number)吗?

这是一个例子:

#include <stdio.h>

int main(void)
{
        int x = 191;
        int the_number = 80;
        printf("x == %d\n", x);
        x -= (x % the_number);
        printf("x - (x %% the_number) == %d\n", x);
        return 0;
}

这是另一个例子。它不像以前那样是一个完整的工作程序,但我想要做的事情更清楚:

#define LIGHT_GRAY 0x0700
#define COLUMNS 80

void pm_putchar(int c, void **ptr)
{
        c &= 0xff;
        c |= LIGHT_GRAY;

        if(c == '\n' | LIGHT_GRAY)
                *ptr += COLUMNS;
        else if(c == '\r' | LIGHT_GRAY)
                *ptr -= (*ptr % COLUMNS);

        **(short **)ptr = (short)c;
        (*ptr) += 2;
}

在上面的示例中,假设VGA 文本缓冲区 ( )*ptr的位置等于或高于该位置。0x0b8000

标签: crounding

解决方案


好吧,如果您只是尝试使用整数除数(您要除以的数字),那么总会有((int) x / theNumber) * theNumber),但是看起来是否更好取决于您。但是,我不知道有什么更好的方法,但是您也许可以重新利用此线程上的一些答案。


推荐阅读