Write a program in C language that can serve as a simple calculator. This calcul
ID: 3762436 • Letter: W
Question
Write a program in C language that can serve as a simple calculator. This calculator keeps track of a single number (of type double) that is called result and that starts out as 0.0. Each cycle allows the user to repeatedly add, subtract, multiply, or divide by a second number. The result of one of these operations becomes the new value of result. The calculation ends when the user enters the letter R for “result” (either in uppercase or lowercase). The user is allowed to do another calculation from the beginning as often as he or she wants. Use the scanf script operator for input.
The input format is shown in the following sample dialog. If the user enters any operator symbol other than +, , *, or /, then display message “UnknownOperatorException is thrown “ and the user is asked to reenter that line of input..
Example Run:
Calculator is on.
result = 0.0
+5
result + 5.0 = 5.0
result = 5.0
*2.2
result * 2.2 = 11.0
result = 11.0
% 10
% is an unknown operation
Reenter, your last line:
* 0.1
result * 0.1 = 1.1
result = 1.1
r
Final result = 1.1
Again? (y/n)
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
int main() {
double result=0;
char ch;
double val;
char in;
printf("Calculator is on. ");
while (true) {
printf("result = %.2lf ", result);
scanf(" %c", &ch);
if (ch != 'r') {
scanf("%lf", &val);
}
switch (ch) {
case '*':
printf("result %c %.2lf = %.2lf ", ch, val, result*val);
result*=val;
break;
case '/':
printf("result %c %.2lf = %.2lf ", ch, val, result/val);
result/=val;
break;
case '+':
printf("result %c %.2lf = %.2lf ", ch, val, result+val);
result+=val;
break;
case '-':
printf("result %c %.2lf = %.2lf ", ch, val, result-val);
result-=val;
break;
case 'r':
printf("Final result = %.2lf ", result);
printf("Again? (y/n):");
scanf(" %c", &in);
if (in == 'n') {
return 0;
}
break;
default:
printf("%c is an unknown operation ", ch);
printf("Reenter, your last line: ");
break;
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.