In c++ program .111 69% 13:07 PM Write a program to model a simple calculator. E
ID: 3871937 • Letter: I
Question
In c++ program
Explanation / Answer
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
void scan_data(char &opr, string &data){
cin >> opr >> data;
}
void do_next_op(char opr, string data, double &acc){
double res;
double res1;
int type = 0;
for (int i = 0; i<data.size(); i++){
if (data[i] == '.'){
type = 1;
break;
}
}
if (atoi(data.c_str()) != 0 && type == 0){
res = atoi(data.c_str());
if (opr == '+'){
acc = acc + res;
}
else if (opr == '-'){
acc = acc - res;
}
else if (opr == '*'){
acc = acc * res;
}
else if (opr == '/'){
if (res == 0){
cout << "Error: division by zero" << endl;
}
else {
acc = acc/res;
}
}
else if (opr == '^'){
acc = pow(acc,res);
}
else {
cout << "Error: invalid operator ";
}
}
else if (atof(data.c_str()) != 0 && type == 1){
res1 = atof(data.c_str());
if (opr == '+'){
acc = acc + res1;
}
else if (opr == '-'){
acc = acc - res1;
}
else if (opr == '*'){
acc = acc * res1;
}
else if (opr == '/'){
if (res == 0){
cout << "Error: division by zero" << endl;
}
else {
acc = acc/res1;
}
}
else if (opr == '^'){
acc = pow(acc,res1);
}
else {
cout << "Error: invalid operator ";
}
}
else {
cout << "Error: invalid operand ";
}
cout << "Result so far is " << acc << endl;
}
int main(){
char opr;
string data;
double acc;
acc = 0;
do {
scan_data(opr,data);
if (opr != 'q' || data != "0")
do_next_op(opr,data,acc);
} while (opr != 'q' || data != "0");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.