Saturday, May 9, 2009

Help with C++! operator variables!?

I am making a c++ calculator and so far i can not go farther than addition


ex.


#include %26lt;iostream%26gt;


using namespace std;





int main ()


{


long int a, b, result;


cout%26lt;%26lt;"Enter a number: ";


cin%26gt;%26gt; a;


cout%26lt;%26lt;"Enter another number: ";


cin%26gt;%26gt; b;


result = a + b;


cout%26lt;%26lt;"The sum is: ";


cout%26lt;%26lt; result;


cout%26lt;%26lt;"\n";


system("pause");


}


so how do i make a variable for operators such as +,-,*,/,%?

Help with C++! operator variables!?
Here is the source:





#include %26lt;iostream%26gt;


using namespace std;





double calc(double a, double b, int operation);





int main() {


double num1, num2, calcAnswer;


int operation;





cout %26lt;%26lt; "Enter operation, \n 1. Multiply \n 2. Divide \n 3. Add \n 4. Minus \n Enter Operation: ";


cin %26gt;%26gt; operation;


cout %26lt;%26lt; "Enter first number: ";


cin %26gt;%26gt; num1;


cout %26lt;%26lt; "Enter second number: ";


cin %26gt;%26gt; num2;





if (operation == 1 || operation == 2 || operation == 3 || operation == 4) {





calcAnswer = calc(num1, num2, operation);





cout %26lt;%26lt; "\n Answer: " %26lt;%26lt; calcAnswer;


cin.ignore();





} else {





cout %26lt;%26lt; "\n\n Invalid operation! \n";


cin.ignore();


}





return 0;


}





double calc(double a, double b, int operation) {





double answer;





if (operation == 1) {





answer = a * b;





} else if(operation == 2) {





answer = a / b;





}else if(operation == 3) {





answer = a + b;





}else if(operation == 4) {





answer = a - b;





}





return (answer);


}





Hope that helps. Sorry I did not have time to comment the code.
Reply:You can email me by going to my profile and click email cayson. Anyways, it is caysonhiivala@hotmail.com. I also emailed this to your yahoo! email. I am glad to help you at any time. I also have some good tips and freebies you can have if you want them, email me. Report It

Reply:Other operators should work just fine, example:





int1 * int2





Try including cstdlib ; see if that makes a difference


No comments:

Post a Comment