将双精度转换为 10 的整数倍
Transform double to int multiple of 10
我有一个从公式计算的双精度列表。例如,其中一个双精度值是 88.32547。我想将它们转换为 10 的最接近的整数倍并将它们放在另一个变量中。
在示例中,双a = 88.32547
会导致int b = 90
或如果double a = -65.32547
会导致int b = -70
。
10*std::round(x/10)
你可能想添加一个 int cast:
int(10*std::round(x/10))
有关详细信息,请参阅 http://en.cppreference.com/w/cpp/numeric/math/round
最简单的方法是这样的
int a = (round(x / 10.0) * 10)
将小数点向左移动(,四舍五入(得到最接近的整数(,然后再次乘以十。
在我无法使用 Round 的情况下,我使用了这样的东西(我需要一些带有负整数的特定内容(:
bottomValue = floor(a/10)*10;
topValue = ceil(a/10)*10;
if(a-bottomValue < topValue-a)
return bottomValue;
else
return topValue;
如果可以使用圆形:
roundValue = round(a/10)*10;
return roundValue;
将数字除以 10,四舍五入到最接近的整数,然后再次乘以 10。
例子:
- 10 × 轮(88.32547/10( = 10 × 轮(8.832547( = 10 × 9 = 90
- 10 × 舍入(−65.32547/10( = 10 × 舍入(−6.532547( = 10 × −7 = −70
对于四舍五入,您可以考虑使用 std::round
。
相关文章:
- 我可以信任表示整数的浮点或双精度来保持精度吗
- C 字符串返回字符串的整数/双精度/长整型值
- 如何防止双精度值到整数的隐式转换
- 野牛/flex:计算器将双精度值解释为整数,所以我添加了 YYSTYPE 双精度 #define 但我有多个编译错误
- 为什么输出是整数而不是双精度?
- 从字符串转换为双精度和整数 - C++
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- C++,遇到将双精度转换为整数的问题
- 用双精度除以整数
- 使用整数初始化列表初始化长双精度的向量
- 如何判断 c++ 向量中的值类型(整数或双精度)?
- 了解双精度转换与整数转换中的整数与截断关系
- 为什么使用 int64_t 会产生错误的结果,而双精度则按预期进行简单的整数乘法
- 将双精度与整数进行比较
- 64 位整数到双精度冲突
- 在编译时将整数和分数部分宏组合成一个新的宏或双精度
- 不确定输出双精度或整数的代码行
- 将 32 位浮点数和不强制转换的 32 位整数与双精度进行比较,当其中一个值可能太大而无法完全适合另一种类型时
- 使用 sprintf 格式化负整数/双精度
- 在c++中是否有一种方法可以将这种格式的输入限制为整数/双精度