在C ++中有电源数字和的问题

时间:2017-02-28 09:29:00

标签: c++

2 ^ 15 = 32768,其数字之和为3 + 2 + 7 + 6 + 8 = 26.

数字2 ^ 1000的数字总和是多少?

目前我正在研究C ++中的数字和。我的程序工作正常但输出不合适。

#include<iostream>
#include<math.h>
using namespace std;

long double calculate(long double n)
{
    long double i,j,temp = 0,sum = 0;
    while(n != 0)
    {
        temp = fmod(n,10);
        sum = sum + temp;
        n = n / 10;
    }
    return sum;
}
int main()
{
    long double i,j,n = 1000,temp = 1,value = 0;
    for(i = 1;i <= n;i++)
    {
        temp = temp * 2;
    }
    cout << "Multiplication is : " << temp << endl;

    value = calculate(temp);
    cout.precision(100);
    cout << "Sum is : " << value << endl;
    return 0;
}

我正在接受这样的o / p。

Multiplication is : 1.07151e+301
Sum is : 1200.63580205668592182366438692042720504105091094970703125

它不应该在points.it应该以数字打印。

4 个答案:

答案 0 :(得分:5)

以二进制表示2 ^ 1000将需要1000位。双打只有64位长(长双精度为80或128位,具体取决于编译器/架构)。所以双打大约代表2 ^ 1000。 calculate的输入不是2 ^ 1000,而是接近80位允许的近似值。该近似值不包含calculate要求的最低位数。

答案 1 :(得分:2)

您不能使用任何原始数据类型来计算2 ^ 1000及其后来的数字总和,因为它是一个很大的数字(但是,在python和ruby这样的语言中,你可以这样做)。

为了在C / C ++中解决这个问题,你必须使用数组(或任何其他线性数据结构,如链表等)并应用类似于通常的数字乘法纸笔方法的逻辑。

首先尝试在2 ^ 1000中找到一个数字的绑定,然后用全零初始化一个大于它的整数数组。将最后一个元素保持为1.现在将数组(将其视为一个大数字,使每个数字位于数组的不同单元格中)乘以2千次,取模数并结转。

以下是上述逻辑的代码:

int ar[303];
int sum =0;
ar[0]=1;
for(int j=1;j<303;j++)
    ar[j]=0;
for(int i=1;i<1001;i++)
{
    ar[0]=2*ar[0];
    for(int k=1;k<303;k++)
        ar[k]=2*ar[k] + ar[k-1]/10;
    for(int j=0;j<303;j++)
        ar[j]=ar[j]%10;
}
for(int i=0;i<303;i++)
sum = sum + ar[i];
cout<<sum;

希望它有所帮助。

答案 2 :(得分:0)

你得到小数点数的原因是因为你将除以10.这不会产生干净的整数,除非小数点前的最后一位数加倍是零。

例如: 376/10 = 37.6

370/10 = 37

要在第12行的代码中解决此更改: n =(n-temp)/ 10;

这将至少从你的金额中减去浮点数。

答案 3 :(得分:0)

最后我解决了我的问题。

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

long double calculate(string n)
{
    long double i,j,temp = 0,sum = 0;
    for (i = 0;i < n.length();i++)
    {
        if(n[i] == '.')
        {
            break;
        }
        sum = sum + (n[i] - 48);
    }
    return sum;
}
int main()
{
    long double i,j,n = 1000,temp = 1,value = 0;
    string str;
    temp = pow(2,n);
    cout << "Power is : " << temp << endl;
    str = to_string(temp);
    cout << str << endl;
    value = calculate(str);
    cout.precision(100);
    cout << "Sum is : " << value << endl;
    return 0;
}
相关问题