在C 中有电源数字总和
Having issues in power digit sum in C++
2^15 = 32768,其数字之和为3 2 7 6 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
它不应该在点。它应该以数字打印。
代表二进制中2^1000的
将占1000位。双打只有64 bit的长度(根据编译器/体系结构,长双打是80或128位)。因此,双打大约代表2^1000。calculate
的输入不是2^1000,而是与80bits允许的接近近似值。该近似值不包含calculate
要概括的最低数字。
您不能使用任何原始数据类型来计算2^1000及以后的数字总和,因为它是一个大数字(但是,在Python和Ruby等语言中,您可以这样做)。
要在C/C 中解决此问题,您必须使用数组(或任何其他线性数据结构(例如链接列表)等),并应用类似于乘法数字的通常的逻辑。
首先尝试在2^1000中找到数字数量的绑定,然后初始化一个大小的整数阵列,其大小大于所有零。将最后一个元素保持在1。现在将数组(将其视为大数字,以使每个数字都在数组的另一个单元格中),用2,000次乘以Modulo并携带。
这是上述逻辑的代码:
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;
希望它有帮助。
用小数点获得总和的原因是因为您将 double 除以10小数点前的最后一位数为零。
示例:376/10 = 37.6
370/10 = 37
在第12行上的代码中求解此更改:n =(n-temp)/10;
这将至少从您的总和中切出浮点数。
最后我解决了我的问题。
#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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在C 中有电源数字总和