【问题标题】:How to force a division to round up [duplicate]如何强制一个部门四舍五入[重复]
【发布时间】:2020-09-17 23:34:16
【问题描述】:

我正在使用 C 语言进行除法,我有 2 个整数,即 n 和 p。我想将 n 除以 p (n/p) 并且总是希望它四舍五入。即使n不进p,结果是小数点后10位小于5,我想强制向上取整,怎么办?

例如,7/3 应该返回 3。

【问题讨论】:

  • 试试(7 + (3-1))/3
  • 一开始我看错了,所以删除了我对 ceil 的评论。我想也许你可以做类似int result = n/p + n%p?1:0

标签: c


【解决方案1】:

您是否正在寻找这样的东西:

#include <stdio.h>

#define ARRAY_SIZE(array) \
    (sizeof(array) / sizeof(array[0]))

int main(void) {
    int n_list[] = { 7, 8, 9, 10, 11, 12 };
    int n = 7;
    int p = 3;
    int result;
    
    for (size_t index = 0; index < ARRAY_SIZE(n_list); index++) {
        n = n_list[index];
        result = n / p;
        if ((p * result) < n) {
            result++;
        }
        printf("result = %d\n", result);
    }

    return 0;
}

输出

result = 3
result = 3
result = 3
result = 4
result = 4
result = 4

试试repl.it

【讨论】:

  • 不需要分支;只需将p - 1 添加到n,然后再划分为无分支解决方案(参见副本)。
  • @ShadowRanger 至少这种方法适用于正值和n == INT_MAX 时,不像p - 1 方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多