Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a very basic calculator in C++

I’m extremely new to C++, I was following a tutorial and wanted to go a bit off what the course said, I attempted to make a basic calculator that instead of just being able to add could subtract, divide and multiply but it still seems to only be able to add, why is this?

  int num1, num2;
  double sum;
  int addType;
  cout << "Type a number: ";
  cin >> num1;
  cout << "Type a second number: ";
  cin >> num2;
  cout << "Do you want to 1. add, 2. subtract, 3. divide or 4. multiply: ";
  cin >> addType;
  if (int addType = 1) {
    sum = num1 + num2;
  }
  else if (int addType = 2) {
    sum = num1 - num2;
  }

  else if (int addType = 3) {
    sum = num1 / num2;
  }
  else if (int addType = 4) {
    sum = num1 * num2;
  }
  
  cout << "Your total is: " << sum;
  
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are creating new variable in if condition part, update condition part to check if it is equal to something with addType == x

int num1, num2;
 double sum;
 int addType;
 cout << "Type a number: ";
 cin >> num1;
 cout << "Type a second number: ";
 cin >> num2;
 cout << "Do you want to 1. add, 2. subtract, 3. divide or 4. multiply: ";
 cin >> addType;
 if (addType == 1) {
   sum = num1 + num2;
 }
 else if (addType == 2) {
   sum = num1 - num2;
 }

 else if (addType == 3) {
   sum = num1 / num2;
 }
 else if (addType == 4) {
   sum = num1 * num2;
 }
 
 cout << "Your total is: " << sum;
 
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading