Random digits

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?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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.
They are not random. Final total is 4613732 and 5702887 is last value of current.
Maybe you have one extra cout statement somewhere in your program.
Ah, you're right. There is a main function that's outputting the returned value sum. Thanks!
Topic archived. No new replies allowed.