我得到的答案是 1364,但正确答案是 1366。
我得到错误的答案是因为我将 double digits = pow(2,1000)
转换为 string dig = std::to_string(digits)
,还是我还有别的东西失踪了吗?
#include <iostream>
using std::endl; using std::cout;
#include <string>
using std::string;
#include <cmath>
int computeSum(string);
int main(void){
double digits = pow(2,1000);
string dig = std::to_string(digits);
cout << computeSum(dig) << endl;
return 0;
}
int computeSum(string dig){
int sum(0);
for(char n : dig)
sum+=(n-48); // or (n-'0')
return sum;
}
编辑:
解决方法:
我需要添加 if (n!='.')
条件,因为 (n-48)
将 .
转换为其 ASCII 值46,给我一个 -2。
for(char n : dig){
if(n!='.')
sum+=(n-48); // or (n-'0')
}
最佳答案
你的答案不对,因为在队列中
double digits = pow(2, 1000);
您将结果存储为 double
,但是 double
在表示这么大的整数时会失去精度,因为它使用 floating point representation .
您应该使用一个整数,并可能在乘法循环中迭代计算数字的总和,每次迭代都会减少结果。否则,你需要使用一个大的 int 库,比如 Boost.Multiprecision .后者的简单示例:
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
int main()
{
using namespace boost::multiprecision;
// Repeat at arbitrary precision:
cpp_int u = 2;
cpp_int result = pow(u, 1000);
int sum = 0;
for (auto elem : result.str()) // use the string representation
sum += elem-'0';
std::cout << result.str() << std::endl; // prints 2^1000
std::cout << sum << std::endl; // prints the sum of the digits
}
编辑
我意识到在这种情况下@HamZa 在您的回答下方的评论是正确的。 double
范围内的 2 的幂由浮点表示忠实地表示,因此在这种情况下不会丢失任何精度。问题确实是出现在字符串表示形式中的 .0000
。但是,如果您使用 3
作为基数,那么所有的赌注都没有了,您不能简单地使用 std::pow
。
关于c++ - 欧拉计划 #16 : Answer 2 digits off,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30467023/