Simple calculator

I am trying to write a program that mimics a calculator. I wrote this c++ code but it always give me the sum. Any help?

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
  #include <iostream>
using namespace std;
float c(float,char,float);
int main()
{
	int a, b;
	char s;
	cout<<"Enter ";
	cin>>a>>s>>b;
	cout<<"Result "<<c(a,s,b)<<endl;
	return 0; 
}
float c(float a,char s, float b)
{
	if (s='+')
	{ return (a+b);}

	else if  (s='-')
		return (a-b);

	else if (s='*')
	return (a*b);

	else if (s='/')
		return (a/b); 
}
= is for assignment, == is for comparison. So you are going to want to fix your if statements. I also would find it easier to use a switch instead.


http://www.cplusplus.com/doc/tutorial/control/ --very bottom of page
you're right, I feel dumb.
I wasn't taught case yet, so i don't want to use case.
is there a way i can say
if (b==0)
return 0;
else
return (a/b);
1
2
3
4
5
6
7
else if( s == '/' && b != 0 )
    return ( a / b );

return 0; //either s != +, - , * , /
               // or b == 0 and s == /
               //because it already checked the previous if statements
               //when you use else if 
I did it like this and it worked fine.
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;
float c(float,char,float);
int main()
{
	int a, b;
	char s;
	char endFlag = 'n'; 
	while (endFlag != 'y')
	{ 
	cout<<"Enter what you want to calculate in the form: "<<endl;
	cout<<"num+num, num-num, num*num, num/num "<<endl;
	cin>>a>>s>>b;
	if (b==0)
	{	cout<<"Division by zero is undefined."<<endl; }
	else 
	{cout<<"Result "<<c(a,s,b)<<endl;}
	cout << "Are you done? Enter y or n: ";
	cin >> endFlag; } 
	return 0; 
}

float c(float a,char s, float b)
{
	if (s=='+')
		 return (a+b);

	else if  (s=='-')
		return (a-b);

	else if (s=='*')
		return (a*b);

	else if (s=='/')
		return (a/b); 
}
1
2
	if (b==0)
	{	cout<<"Division by zero is undefined."<<endl; }
you may want to change that to if( s == '/' && b == 0 ) otherwise what happens if you try and do 4 + 0? You will get an error saying you can't divide by zero. One more thing to mention you should format your main function neatly like the calculation function it makes things much easier to read.
Yes, that is my mistake.
I changed it and I tried all different values and it returned what I wanted. Thanks for your help.
Topic archived. No new replies allowed.