【问题标题】:how to round a number to N decimal places in C++? [closed]如何在 C++ 中将一个数字四舍五入到 N 个小数位? [关闭]
【发布时间】:2022-07-26 07:46:41
【问题描述】:

我想将一个数字四舍五入到小数点后 10 位,但它返回 '6.75677',虽然它可以返回 '6.7567653457'

#include <iostream>
#include <cmath>
using namespace std;

double rounded(double number, int N)
{
    return round(number * pow(10, N)) / pow(10, N); // i've chanched float to double
}

int main()
{
    double value = 6.756765345678765; 
    cout << rounded(value, 10)
}

我希望看到一个函数返回四舍五入的数字

坦率地说,我会在 python 中看到函数“round”的替代方法

print(round(6.756765345678765, 10))

【问题讨论】:

  • A float 首先“没有”小数点后 10 位四舍五入。它不能精确地表示值以获取该信息 - 两个“相邻”有效float 值之间的最小差异远大于 10^-10。 (别介意任何类型的数字根本就没有“有”数字;这是一个单独的主题。)
  • 这能回答你的问题吗? What is the difference between float and double?
  • 我也尝试过 double 类型,但还是不行。那么,如何以完美的精度对数字进行四舍五入呢?
  • “准确无误” 浮点数是个难题

标签: python c++


【解决方案1】:
cout << fixed << setprecision(10) << value << endl

【讨论】:

  • 是的,它有效,但我宁愿使用'cout.precision(11)'
猜你喜欢
  • 1970-01-01
  • 2010-09-14
  • 2023-02-08
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多