0
How to make a calculator ? Pls post the program
2 Answers
+ 1
well try one of these two codes :
code 1
---------------
#include <iostream>
using namespace std;
//Function prototype
int solve(int, int, char);
int main()
 {
 //Declare variables
 int solution, num1, num2;
 char oper;
 //Output
 cout << "Calculator\n----------\n" << endl;
 cout << "Syntax:\n" << endl;
 cout << "1 + 3\n" << endl;
 cout << "Operators: +, -, *, /\n" << endl;
 cout << "Equation: ";
 //Input
 cin >> num1 >> oper >> num2;
 //Solve and output
 solution = solve(num1, num2, oper);
 cout << "Answer: " << solution << endl;
 //Pause [until enter key] and exit
 cin.ignore(); //Enter key from last cin may be passed, ignore it.
 cin.get();
 return 0;
 }
int solve(int num1, int num2, char oper)
 {
 //Switch oper
 switch(oper)
  {
  case '+':
   return num1 + num2;
  case '-':
   return num1 - num2;
  case '*':
   return num1 * num2;
  case '/':
   return num1 / num2;
  default:
   cout << "\nIncorrect operation!  Try again: ";
   cin >> num1 >> oper >> num2;
   solve(num1, num2, oper);
  }
 }
code 2
-----------
To understand this example, you should have the knowledge of following C++ programming topics:
    C++ switch..case Statement
    C++ break and continue Statement
This program takes an arithmetic operator (+, -, *, /) and two operands from an user and performs the operation on those two operands depending upon the operator entered by user.
# include <iostream>
using namespace std;
int main()
{
    char op;
    float num1, num2;
    cout << "Enter operator either + or - or * or /: ";
    cin >> op;
    cout << "Enter two operands: ";
    cin >> num1 >> num2;
    switch(op)
    {
        case '+':
            cout << num1+num2;
            break;
        case '-':
            cout << num1-num2;
            break;
        case '*':
            cout << num1*num2;
            break;
        case '/':
            cout << num1/num2;
            break;
        default:
            // I
0
# include <iostream>
using namespace std;
int main() {
  char op;
  float num1, num2;
  cout << "Enter operator: +, -, *, /: ";
  cin >> op;
  cout << "Enter two operands: ";
  cin >> num1 >> num2;
  switch(op) {
    case '+':
      cout << num1 << " + " << num2 << " = " << num1 + num2;
      break;
    case '-':
      cout << num1 << " - " << num2 << " = " << num1 - num2;
      break;
    case '*':
      cout << num1 << " * " << num2 << " = " << num1 * num2;
      break;
    case '/':
      cout << num1 << " / " << num2 << " = " << num1 / num2;
      break;
    default:
      // If the operator is other than +, -, * or /, error message is shown
      cout << "Error! operator is not correct";
      break;
  }
  return 0;
}
Run Code
Output
Enter operator: +, -, *, /: -    
Enter two operands: 3.4 8.4
3.4 - 8.4 = -5
Thi



