c++ - 在 C++ 中处理存储在 double 中的大整数时如何避免舍入/精度错误?

标签 c++ precision

<分区>

问题

我正在尝试解决以下问题:

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?

Source

由于精度错误,我一直收到错误的输出。但是,正如您在下面看到的,我尽量确保没有任何东西被舍入,或者因为精度而丢失。我编写的代码与所需的输出 (1366) 相差两倍 (1364)。如何优化我的代码才能不因精度和舍入错误而丢失任何其他内容?

我的代码

#include <iostream>
#include <tgmath.h>
#include <string>
using namespace std;

int main() {
    int sum=0;
    double N = pow(2.0, 1000.0);
    string num = to_string(N);
    for(int i=0; i<num.size(); i++) {
        sum += num[i] - '0';
    }
    cout<<sum;
    return 0;
}

最佳答案

根据 WolframAlpha2^1000 的结果是

10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

这永远不会适合 intdouble。您需要找到一个支持非常大数字的库。 The GNU Multiple Precision Arithmetic Library 就是这样一个库。

关于c++ - 在 C++ 中处理存储在 double 中的大整数时如何避免舍入/精度错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54895472/

相关文章:

php - 货币的浮点精度 : using "round" function in MySQL query vs PHP vs Javascript

json - 将数字从 float64 转换为 Int64 不正确

c++ - 接收 MFC 对话框的 PostMessage 消息

c++ - 三次贝塞尔曲线上到给定点的最近点

c++ - opengl矩阵乘法

java - 格式化 double 到 6 位小数精度

python - 无法让 numpy 添加长 double

c++ - 这种精度损失发生在哪里以及如何防止它发生?

c++ - 如何确定 MSADO 命令参数的大小

c++ - C++ 是开源项目吗?哪个社区开发它?