Function Bug

Right so I thought hey lets make a calculator program to practice my function noobie skills. This is my code so far, and whenever I go to subtracting(), the answer is always 0?!?!

Thanks in advance

Arc
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
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

int subtractionOne;
int subtractionTwo;
int subtractionTotal;

int subtraction() {
	int subtractionTotal = subtractionOne + subtractionTwo;	
	
	
	cin >> subtractionOne >> subtractionTwo;
	cout << subtractionTotal;
	
	return subtractionTotal;
}

int main () {
	int choose;	
	
			system ("clear");
	
	cout << "Press one for adding, two for subtracting.";
	cin >> choose;
	
	if(choose == 1) {
		
		subtraction();
		
	}
	
		

	return 0;
}

I think this is right
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
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;

int subtractionOne;
int subtractionTwo;
int subtractionTotal;

int subtraction() {
		
	
	
	cin >> subtractionOne >> subtractionTwo;
        int subtractionTotal = subtractionOne + subtractionTwo;
	cout << subtractionTotal;
	
	return subtractionTotal;
}

int main () {
	int choose;	
	
			system ("clear");
	
	cout << "Press one for adding, two for subtracting.";
	cin >> choose;
	
	if(choose == 1) {
		
		subtraction();
		
	}
	
		

	return 0;
}

line 13
Last edited on
Several problems with this code. You have a subtractionTotal variable in the global scope and another one in subtraction(). This code:

1
2
3
4
5
6
7
8
int subtractionTotal = subtractionOne + subtractionTwo;	
	
	
	cin >> subtractionOne >> subtractionTwo;
	cout << subtractionTotal;
	
	return subtractionTotal;


needs to be rearranged. The value of subtractionTotal will always end up being zero because at the time you are assigning the value of subtractionOne + subtractionTwo, the user has not input any values, you are then attempting to output that 0 value. In your main function you prompt for the user to enter 1 for adding, two for subtracting, but your subtraction function only executes if you select to add 1, and the function doesn't actually subtract... it adds....
Ahh thanks mate that worked and I also was using + instead of - LOL thanks
Topic archived. No new replies allowed.