c - 如何将整数向下舍入到最接近的数字倍数?
问题描述
我正在尝试将整数四舍五入到最接近的数字倍数。
说数字等于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
解决方案
好吧,如果您只是尝试使用整数除数(您要除以的数字),那么总会有((int) x / theNumber) * theNumber)
,但是看起来是否更好取决于您。但是,我不知道有什么更好的方法,但是您也许可以重新利用此线程上的一些答案。
推荐阅读
- cloud-foundry - PCF:如何找到您拥有开发人员权限的所有空间的列表
- vb.net - 按变量名使用字典
- amazon-web-services - 仅在 AWS Elastic Beanstalk 网站上部署更改的文件
- node.js - 在 loopback4 中扩展实体与扩展模型
- c - 如何在 Windows 上使用 libssh 在 C 中执行端口转发
- pandas - 只有一列的数据框,删除 nans 不起作用
- python - 在函数之外或在其他函数中使用变量?
- python - 使用 discord.py 使用 bot 命令写入文本文件
- git - Gitlab-ci 用于同一存储库中的特定目录
- mysql - MySQL Workbench Visual Explain 不起作用