### 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 "=".

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990`` `````` #include #include #include #include #include #include #include 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:
 ``12345678910111213141516171819202122232425262728293031`` ``````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.