gpt4 book ai didi

c++ - 安全地舍入到下一个更小的倍数

转载 作者:太空狗 更新时间:2023-10-29 20:37:44 27 4
gpt4 key购买 nike

考虑:

int a, b;
int c = b * (a / b)

我认为它对正数的作用应该很清楚:c 被设置为 b 的倍数,b 相对于 a 的下一个较小值。

例子:令b = 2,则:

a = 0 => c = 0
a = 1 => c = 0
a = 2 => c = 2
a = 3 => c = 2

然而,对于负数,它以相反的方式工作:它取 b 的下一个更大(负数较小)的倍数。 同时选择下一个更小(更负)的 b 倍数的最佳方法是什么?

最佳答案

怎么样:

#include <cstdlib>
#include <iostream>

int round_down(int val, int unit) {
std::div_t div_result = std::div(val, unit);
int candidate = div_result.quot * unit;
return candidate <= val ? candidate :
unit >= 0 ? candidate - unit :
candidate + unit;
}

int main() {
std::cout << round_down(9, 7) << std::endl;
std::cout << round_down(13, 2) << std::endl;
std::cout << round_down(15, 3) << std::endl;

std::cout << round_down(-9, 7) << std::endl;
std::cout << round_down(-13, 2) << std::endl;
std::cout << round_down(-15, 3) << std::endl;

std::cout << round_down(9, -7) << std::endl;
std::cout << round_down(13, -2) << std::endl;
std::cout << round_down(15, -3) << std::endl;

std::cout << round_down(-9, -7) << std::endl;
std::cout << round_down(-13, -2) << std::endl;
std::cout << round_down(-15, -3) << std::endl;
}

请注意,在 C++11 之前,内置除法运算符 / 的舍入方向是实现定义的。所以,我改用 std::div()。引自 cppreference (强调我的):

The binary operator / divides the first operand by the second (after usual arithmetic conversions).
For integral operands, it yields the algebraic quotient.
The quotient is rounded in implementation-defined direction. (until C++11)
The quotient is truncated towards zero (fractional part is discarded). (since C++11)
...
Note: Until C++11, if one or both operands to binary operator % were negative, the sign of the remainder was implementation-defined, as it depends on the rounding direction of integer division. The function std::div provided well-defined behavior in that case.

关于c++ - 安全地舍入到下一个更小的倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33956318/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com