Write a program to model a simple calculator. Each data line should consist of t
ID: 3856026 • Letter: W
Question
Write a program to model a simple calculator. Each data line should consist of the next operation to be preformed from the list below and the right operand. Assume the left operand is the accumulator value (initial value of 0). You need a function scan data with two output parameters that returns the operator and right operand scanned from the data line. You need a function do next op that performs the required operation. do next op has two input parameters (the operator and operand) and one input/output parameter (the accumulator). The valid operators are: + add - subtract multiply / divide power (raise left operand to the power of the right operand) 1 q quit Your calculator should display the accumulator value after each operation. A sample run follows. + 5.0 Result so far is 5.0 2
Result so far is 25.0 / 2.0
Result so far is 12.5 q 0
Final result is 12.5 (IN C WITH COMMENTS)
Explanation / Answer
#include <stdio.h>
#include<stdlib.h>
#include <math.h>
//function prototype
void scan_data(char sign, float num);
float do_next_op(char sign, float num, float sum);
int main()
{
printf("Hit enter to turn the calculator on");
scan_data('x',1);
return 0;
}
//function scan_data
void scan_data(char sign, float num)
{
char op, temp;
float sum;
sum = 0;
//this do-while takes the operator and operands as input and passes it on to the do_next_op function to do the calculation. If you press q to quit it will exit from here
//the loop will run until it encounters q.
do{
scanf("%c", &temp);
printf("Enter an operator [^,*,/,+,-, q(quit)]: ");
scanf("%c", &op);
if(op=='q'||op=='Q')
{
printf("The last result was %1.2f ", sum);
exit(0);
}
else
{
printf("Enter a number to calculate for: ");
scanf("%f", &num);
printf("%c%1.2f ",op ,num);
sum = do_next_op(op, num, sum);
}
}while(op!='q'||op!='Q');
}
//function do_next_op
float do_next_op(char sign, float num, float sum)
{
//this function consists of the below switch case construct. It gets the operator and operands to do the specific operations on the operands.
//it displays the result after each operation
switch(sign)
{
case('^'):
sum = pow(sum,num);
printf("The result so far is %1.2f ", sum);
return sum;
break;
case('*'):
sum = sum * num;
printf("The result so far is %1.2f ", sum);
return sum;
break;
case('/'):
if(num<=0)
{
printf("Can not divide by 0 ");
printf("The result so far is %1.2f ", sum);
return sum;
}
else if(num>0)
{
sum=sum/num;
printf("The result so far is %1.2f ", sum);
return sum;
}
break;
case('+'):
sum=sum+num;
printf("The result so far is %1.2f ", sum);
return sum;
break;
case('-'):
sum=sum-num;
printf("The result so far is %1.2f ", sum);
return sum;
break;
default:
break;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.