Hello Cplusplus, I have been working on a simple calculator program. I have the essential components put together and have created a function to perform various operations. I would just like some suggestions on how to tidy my code up a bit, remove any unneeded code, and to learn about any other methods to do this.
Thank you, I appreciate your help and suggestions!
Code:
#include<iostream>
using namespace std;
double calculate(double x, double y)
{
cout<<"Select the operation you wish to perform(+,-,*,/):";
char operate;
cin>>operate;
double answer;
if(operate=='+')
answer=x+y;
else if(operate=='-')
answer=x-y;
else if(operate=='/')
answer=x/y;
else if(operate=='*')
answer=x*y;
else
cout<<"That is not an operation I know.";
return answer;
}
int main()
{ cout<<"\t\t\t***Simple Calculator***\n\n";
double a;
double b;
double solution;
cout<<"Please enter two numbers seperated with a space\n";
cin>>a>>b;
solution=calculate(a, b);
cout<<solution<<endl;
Nisheeth, thanks for the suggestion. The only problem is when I use a switch I get a run-time error.
"Run-Time Check Failure #3 - The variable 'answer' is being used without being initialized."
Ahhh, thank you so much. I tried initializing answer to 0 earlier and that didn't work for some strange reason. However, when I changed 'operate' to the char type it solved the problem.
Thanks for the suggestion Dinesh, I have no desire to incorporate graphics into this particular project. My only intent was to create a very simple calculator program. I do agree, however, that the 2 steps must be consolidated into one single step to be more efficient.