gpt4 book ai didi

c++ - 通过四舍五入 boost rational_cast ?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:40 27 4
gpt4 key购买 nike

我怎样才能做 rational_cast<int64_t>四舍五入?

目前我正在做这样的黑客攻击:

boost::rational<int64_t> pts = ..., time_base = ...;
int64_t rounded = std::llround(boost::rational_cast<long double>(pts / time_base));

但我希望能够在不涉及 float 的情况下“正确地”完成它。

最佳答案

舍入本质上是有损的。

想到的最快的黑客攻击就是简单地使用内置行为(即 floor-ing 或 trunc-ing 结果)并偏移一半:

Live On Coliru

#include <iostream>
#include <fstream>
#include <boost/rational.hpp>

int main() {
using R = boost::rational<int64_t>;
for (auto den : {5,6}) {
std::cout << "---------\n";
for (auto num : {1,2,3,4,5,6}) {
R pq(num, den);
std::cout << num << "/" << den << " = " << pq << ": "
<< boost::rational_cast<int64_t>(pq + R(1,2)) << "\n";
}
}
}

打印

---------
1/5 = 1/5: 0
2/5 = 2/5: 0
3/5 = 3/5: 1
4/5 = 4/5: 1
5/5 = 1/1: 1
6/5 = 6/5: 1
---------
1/6 = 1/6: 0
2/6 = 1/3: 0
3/6 = 1/2: 1
4/6 = 2/3: 1
5/6 = 5/6: 1
6/6 = 1/1: 1

关于c++ - 通过四舍五入 boost rational_cast ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46929544/

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