I'm trying to learn C++ by tackling problems on sites like projecteuler. This happened when I tried to solve one of the problems (problem 2 in particular):
The correct value is 4613732 which is the final output from within my while loop. However, the total output outside of the loop is incorrect. It's giving me 46137325702887. What's with the extra digits?
int problemTwo(){
int total = 2;
int sum;
int current = 2;
int prev = 1;
bool cap = true;
while(cap){
cout << prev << endl;
cout << current << endl;
sum = current + prev;
if(sum%2==0){
total = total + sum;
}
prev = current;
current = sum;
if(current>=4000000){
cap=false;
}
cout << current << endl;
cout << total << endl;
cout << endl;
}
cout << "final total: " << total;
return sum;
}
I'm sure my code could be simplified to a few lines but in an effort to clearly understand every line of code I'm keeping everything very simple for now.