vendredi 17 septembre 2021

C++ excutes all if statements even if all other are false [closed]

I built a simple calculator but I came across a strange bug.

    //perform operation
  if ( ChooseOP = 1 ) {
    FunctionAdd(Num1 , Num2) ;
  }
  if ( ChooseOP = 2 ) {
  FuntionSub(Num1 , Num2) ;
  }
  if ( ChooseOP = 3 ) {
    FunctionMul(Num1 , Num2) ;
  }
  if ( ChooseOP = 4 ) {

    FunctionDiv(Num1 , Num2) ;
  }
  else {
    cout << "Incorrect operation" ;
  }

If you input 1 the program will not only execute the right IF statement but it will also consider the other three if statements true as well which they are not. any ideas what's causing the problems.

Here is the entire program if you are curious:

#include <iostream>
#include <cmath>
using namespace std ;

double FunctionAdd (double i , double j) // add numbers
   {
     double sumation = i + j ;
     cout << "The Sum of two number " << i << " & " << j << " = " << round(sumation*100)/100 << endl ;
     return 0 ;
   }
double FuntionSub (double i, double j) // minus number
   {
     double Substraction = i - j ;
     cout << "The Substraction of two number " << i << " & " << j << " = " << round(Substraction*100)/100 << endl ;
     return 0 ;
   }
double FunctionMul (double i , double j) // multiply numbers
  {
    double Multiplication = i * j ;
    cout << "The Product of two number " << i << " & " << j << " = " << round(Multiplication*100)/100 << endl ;
    return 0 ;
  }
double FunctionDiv(double i , double j) // divide nums
{
  double Division = i / j ;
  cout << "The Division of two number " << i << " & " << j << " = " << round(Division*100)/100 << endl ;
  return 0 ;
}
int main ()
{
  //vars
  double Num1 , Num2 ;
  int ChooseOP ;
  string line1 = "Enter 1 to perfom " ;
  //get numbers
  cout << "Enter first numbers: \n" ;
  cin >> Num1  ;
  cout << "Enter second numbers: \n" ;
  cin >> Num2 ;
  //choose operation
  cout << "Choose which operation to perform: \n" ;
  cout << line1 << "Addition" << endl ;
  line1[6] = '2' ;
  cout << line1 << "Substraction" << endl ;
  line1[6] = '3' ;
  cout << line1 << "Multiplication" <<  endl ;
  line1[6] = '4' ;
  cout << line1 << "Division" << endl ;
  //get op
  cin >> ChooseOP ;
  //perform operation
  if ( ChooseOP = 1 ) {
    FunctionAdd(Num1 , Num2) ;
  }
  if ( ChooseOP = 2 ) {
  FuntionSub(Num1 , Num2) ;
  }
  if ( ChooseOP = 3 ) {
    FunctionMul(Num1 , Num2) ;
  }
  if ( ChooseOP = 4 ) {

    FunctionDiv(Num1 , Num2) ;
  }
  else {
    cout << "Incorrect operation" ;
  }
  return 0 ;
}

Aucun commentaire:

Enregistrer un commentaire