Skip to content

Instantly share code, notes, and snippets.

@lix19937
Created May 12, 2026 08:00
Show Gist options
  • Select an option

  • Save lix19937/888ca1976d942a11f2344f265a130a40 to your computer and use it in GitHub Desktop.

Select an option

Save lix19937/888ca1976d942a11f2344f265a130a40 to your computer and use it in GitHub Desktop.
round_by_factor
#include <stdio.h>
#include <cmath>
#include <iostream>
/*
def round_by_factor(number: int, factor: int) -> int:
"""Returns the closest integer to 'number' that is divisible by 'factor'."""
return round(number / factor) * factor
factor=32
h_bar = max(factor, round_by_factor(720, factor))
print(h_bar)
a = 720/factor
print(a)
ra = round(a)
print(ra)
*/
/**
* 返回最接近 'number' 且能被 'factor' 整除的整数。
* 遵循 Python 的 round() 逻辑(银行家舍入法)。
*/
int64_t round_by_factor(int64_t value, int64_t factor) {
if (factor == 0) return 0;
double div = static_cast<double>(value) / factor;
// 使用 std::nearbyint 模拟 Python 的“五成双”逻辑
double rounded = std::nearbyint(div);
return static_cast<int64_t>(rounded) * factor;
}
void t1() {
std::cout << "8 / 3 舍入到 3 的倍数: " << round_by_factor(8, 3) << std::endl;
std::cout << "5 / 10 舍入到 10 的倍数: " << round_by_factor(5, 10) << std::endl;
std::cout << "15 / 10 舍入到 10 的倍数: " << round_by_factor(15, 10) << std::endl;
std::cout << "720 / 32 舍入到 32 的倍数: " << round_by_factor(720, 32) << std::endl;
std::cout << "465 / 32 舍入到 32 的倍数: " << round_by_factor(465, 32) << std::endl;
}
int main(){
auto roundByFactor = [](int64_t value, int64_t factor) -> int64_t {
return std::round(static_cast<double>(value) / factor) * factor;
};
int64_t factor=32;
auto a = roundByFactor(720, factor);
printf("%d\n", a);
//-----------------------------------------------------------------------
auto myround_by_factor = [](int64_t value, int64_t factor) -> int64_t {
if (factor == 0) return int64_t(0);
double div = static_cast<double>(value) / factor;
double rounded = std::nearbyint(div);
return static_cast<int64_t>(rounded) * factor;
};
auto b = myround_by_factor(720, factor);
printf("%d\n", b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment