2. Write these functions definitions:
d) Function div2Numbers () that divides 2 integers.
Compile and test your function with the following main function:
int main()
1
char op;
cout<<"Enter + to add 2 integers\n";
cout<<"Enter - to subtract 2 integers\n";
cout<<"Enter x to multiply 2 integers\n";
cout<<"Enter / to divide 2 integers\n";
cout<<"Enter the operator required: ";
cin>>op;
switch (op)
{
case '+': add2 Numbers (); break;
case '-': sub2 Numbers (); break;
case 'x' : mul2 Numbers (); break;
case '/': div2 Numbers (); break;
default: cout<<"Invalid operator entered\n";
break;
}
a) Function add2 Numbers () that adds 2 integers.
b) Function sub2 Numbers () that subtracts 2 integers.
c) Function mul2Numbers () that multiplies 2 integers.​

Respuesta :

Answer:

Complete the code with the following code segment:

void add2Numbers(){

   int num1, num2;

   cout<<"Enter any two numbers: ";

   cin>>num1>>num2;

   cout<<num1+num2;

}

void sub2Numbers(){

   int num1, num2;

   cout<<"Enter any two numbers: ";

   cin>>num1>>num2;

   cout<<num1-num2;

}

void mul2Numbers(){

   int num1, num2;

   cout<<"Enter any two numbers: ";

   cin>>num1>>num2;

   cout<<num1*num2;

}

void div2Numbers(){

   int num1, num2;

   cout<<"Enter any two numbers: ";

   cin>>num1>>num2;

if(num2==0){

cout<<"Division by 0 is invalid";

}else{

   cout<<(float)num1/num2;}

}

Explanation:

The function added to this solution are:

  • add2Numbers
  • sub2Numbers
  • mul2Numbers
  • div2Numbers

Each of the functions

  • declares two integers num1 and num2
  • prompt user for inputs
  • gets user inputs from the user

For add2Numbers() function:

This line adds the two integer numbers and prints the result

   cout<<num1+num2;

For sub2Numbers() function:

This line subtracts the two integer numbers and prints the result

   cout<<num1-num2;

For mul2Numbers() function:

This line multiplies the two integer numbers and prints the result

   cout<<num1*num2;

For div2Numbers() function:

This if condtion checks if the denominator is 0

if(num2==0){

If yes, the following is printed

cout<<"Division by 0 is invalid";

If otherwise, the division is calculated and the result is printed

   cout<<(float)num1/num2;

See attachment for complete program

Ver imagen MrRoyal