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:

  1. starting sum 1, although highly unlikely change result.

  2. using floating-point introduces inaccuracies. more change result in case still won't, because need 10 significant digits.

  3. 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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -