C++ 4. Write a function named calculate ( ) that has two integer numbers paramet
ID: 3679425 • Letter: C
Question
C++
4. Write a function named calculate ( ) that has two integer numbers parameter named x and y and char parameter named operator. The passed char represents a type of mathematical operation such as “+” “ -” “ *” “ /” . your function should apply the corresponding mathematical operation on integers X and y . and return an integer result . make sure your main ( ) will ask the user to input data, call the function , and display the result . test the function by passing various data to it .
Hint: the function prototype can be int calculator(int, int,char).
Explanation / Answer
#include<iostream>
using namespace std;
int calculator(int, int,char);
int main(){
int x, y;
char op;
cout<<"Enter value of x and y : "<<endl;
cin>>x>>y;
cout<<"Enter operator (+,-,*,/) : ";
cin>>op;
int result = calculator(x,y,op);
cout<<"Result: "<<result<<endl;
return 0;
}
int calculator(int x, int y,char op){
int result = 0;
switch(op){
case '+':
result = x+y;
break;
case '-':
result = x-y;
break;
case '*':
result = x*y;
break;
case '/':
result = x/y;
break;
default:
cout<<"Invalid operator"<<endl;
}
return result;
}
/*
Output:
Enter value of x and y :
3
4
Enter operator (+,-,*,/) : +
Result: 7
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.