避免舍入错误(专门浮动)C ++ [英] avoid rounding error (floating specifically) c++

查看:45
本文介绍了避免舍入错误(专门浮动)C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/我最近一直在讨论C ++.

http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/ I have been about this lately to review C++.

尽管我们知道四舍五入的含义,但一般的计算机班教授往往不会讲这些小问题.

In general computing class professors tend not to cover these small things, although we knew what rounding errors meant.

有人可以帮助我避免舍入错误吗?

Can someone please help me with how to avoid rounding error?

本教程显示了示例代码

#include <iomanip>
int main()
{
    using namespace std;
    cout << setprecision(17);
    double dValue = 0.1;
    cout << dValue << endl;
}

此输出

0.10000000000000001

0.10000000000000001

默认情况下,浮点数保持6位精度.因此,当我们覆盖默认值并要求更多值时(在这种情况下为17 !!),我们可能会遇到截断的情况(本教程也对此进行了说明).对于double,最高为16.

By default float is kept 6-digits of precisions. Therefore, when we override the default, and asks for more (n this case, 17!!), we may encounter truncation (as explained by the tutorial as well). For double, the highest is 16.

通常,优秀的C ++程序员如何避免舍入错误?你们总是看数字的二进制表示吗?

In general, how do good C++ programmers avoid rounding error? Do you guys always look at the binary representation of the number?

谢谢.

推荐答案

该主题的规范建议是阅读,作者:大卫·戈德堡(David Goldberg).

The canonical advice for this topic is to read "What Every Computer Scientist Should Know About Floating-Point Arithmetic", by David Goldberg.

这篇关于避免舍入错误(专门浮动)C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆