Home > front end >  Creating a very basic calculator in C
Creating a very basic calculator in C

Time:06-22

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;
  
}

CodePudding user response:

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;
 
}

CodePudding user response:

you defined addType multiple times. It should be:

if (addType == 1)

= means assign a value.

CodePudding user response:

if (int addType = 1)

means assign 1 to "addType", "addType" is alway 1, so condition alway is true.You will only ever be able to add.

CodePudding user response:

if(int addType = 1) it is a expression which defines a variable named addType and assigns it's value equal to 1. so it becomes if(1) which is true. so instead of this write as if( addType ==1)

  • Related