2 answers
Best answer
// Program to perform given operation on two input integers
#include<iostream.h> {
void main()
{
int a, b, c, d, e;
char oper;
float f;
cout<<"Enter the first number:";
cin>>a;
cout<<"Enter the operator:";
cin>>oper;
cout<<"Enter the second number:";
cin>>b;
if (oper=='+')
{
c = a +b;
cout <<"the result is:"<<c;
else if(oper=='-')
{
d=a-b; cout<<"the result is:"<<d;
} else if (oper=='*') {
e = a*b; cout<<"the result is:"<<e;
} else if (oper=='/')
if (b==0)
{
} else
{
f=(float)a/b;
cout<<"the result is : "<<f;
}
}
else
cout<<"invalid operator";
}
Answer: A program that reads two numbers and an operator and uses the arithmetic operators +, -, *, / and % to compute the result.
#include <iostream>
using namespace std;
int main()
{
int a, b;
char op;
cout << "Enter first number: ";
cin >> a;
cout << "Enter operator (+ - * / %): ";
cin >> op;
cout << "Enter second number: ";
cin >> b;
if (op == '+')
cout << "Result = " << a + b;
else if (op == '-')
cout << "Result = " << a - b;
else if (op == '*')
cout << "Result = " << a * b;
else if (op == '/' || op == '%')
{
if (b == 0)
cout << "Division by zero is not allowed";
else if (op == '/')
cout << "Result = " << (float)a / b;
else
cout << "Result = " << a % b;
}
else
cout << "Invalid operator";
cout << endl;
return 0;
}How it works:
- The arithmetic operators used are
+,-,*,/and%(remainder, only for integers). - The relational operator
==and the logical operator||(OR) are used to decide which operation to perform. (float)a / bgives a decimal answer; without the cast, integer division would drop the fractional part.- Division by zero is checked first, because it is not allowed.
Sample run: 7, /, 2 prints Result = 3.5.
Your answer
Log in or create a free account to answer this question.