project Euler #13 c++ -
this question has answer here:
https://projecteuler.net/problem=13
work out first ten digits of sum of following one-hundred 50-digit numbers.
i try solve using c++ in xcode. saved numbers in file , built got wrong answer. here code:
#include <fstream> #include <iostream> using namespace std; int main(void) { double sum = 1; double num; ifstream fin("/users/pwd/programs/projecteuler13/num.txt"); while (fin) { fin >> num; sum += num; } fin.close(); cout.precision(12); cout << sum << endl; return 0; }
i got result: 5.59087976462e+51
so first 10 digits of sum: 5590879764. wrong. wrong code?
several issues can see:
starting sum 1, although highly unlikely change result.
using floating-point introduces inaccuracies. more change result in case still won't, because need 10 significant digits.
the serious problem: incorrectly looping on input. see why iostream::eof inside loop condition considered wrong?. cause add last number twice. correct way loop on input stream is:
while (fin >> val) { //do val. }
Comments
Post a Comment