Simple Calculator

Hey all (Small logical error?),

I am supposed to design a Calculator on C++ that works like an actual calculator(starts with 0 and values keyed in are added to the sum.) However, when i try to code this, the value does not add upon itself or subtracts. it resets to its initialised value each time(0). Here is the code.

basically, what i need is for it to work like a real calculator which stores the values of what was previously keyed in. And exits upon user pressing "=".

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  #include<iostream>
#include<iomanip>
#include<cstdlib>
#include<ctime>
#include<cstring>
#include<cctype>
#include<cmath>

using namespace std;

void getInfo(char&,double&);
float pow(float);

int main()

{

	cout << "calculator is on" << endl << endl;
	char a,x;
	double y=0;

	
	getInfo(x,y);
	
	

}


void getInfo(char& x, double & y)

{
	
	char equal;	
	int sum1,sum2,sum3;   
	cout << "==> " << y << endl << endl;
	
	while (equal != '=')
	
	{
		cin >> x >> y;

		if (x ='+')
		
		{
			y=y;
			sum1=y+y;
			cout << "==>" << y << endl << endl;
		}
	
		else if(x ='-')
		
		{
			y=y-y;
			cout << "==>" << y << endl << endl;
		}
		
		else if(x = '*')
		
		{
			int z;
			y=y*z;
			cout << "==>" << y << endl << endl;
		}
		
		else if (x = '/')
		
		{
			y=y/y;
			cout << " ==>" << y << endl << endl;
		}
		
		else if (x = '^')
		
		{
			y=y*y;
			cout << " ==>" << y << endl << endl;
		}
		
		else if ( x = 's')
		
		{
		
			y=sqrt(y);
		}
	}

}

Last edited on
= assigns a value
== compares two values

within each if you need to replace = with ==
still cant work
still cant work
Yes, you really need to improve your sense of logic.

y is reset because you implemented it so. To get a valid result use another variable, like so:
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
void getInfo(char& x, double & y)

{
	
	char equal;	
	double result = 0; // Note: initialize it to 0
	int sum1,sum2,sum3;   // I don't know why you want three of them?
	cout << "==> " << y << endl << endl;
	
	while (equal != '=')
	
	{
		cin >> x >> y; // here you reset x and y

		if (x =='+')
		
		{
			y=y; // no effect
			sum1=y+y; // neither this
			result += y; // add y to the result
			cout << "==>" << y result << endl << endl; // show the result
		}
	
		else if(x =='-')
		
		{
			y=y-y;
			result -= y; // subtract y from the result
			cout << "==>" << y result << endl << endl;
		}
...


I don't see the use of the parameter char& x, double & y. When you call getInfo on line 23 x is unitialized and contains a random value.

result would be a subject for return
Topic archived. No new replies allowed.