Write a program in the C language that can serve as a simple calculator. This ca
ID: 3762601 • Letter: W
Question
Write a program in the 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
Input: +5
Output: Result + 5.0 = 5.0
result = 5.0
Input: *2.2
Output: result * 2.2 = 11.0
result = 11.0
Input: % 10
Ouput: % is an unknown operation. Reenter, your last line:
Input: * 0.1
Output: result * 0.1 = 1.1
result = 1.1
Input: r
Output: Final result = 1.1. Again? (y/n)
Explanation / Answer
#include <stdio.h>
int main(void) {
// your code goes here
float result=0,input;
char op,tp;
int g=1;
printf("Calculator is on. ");
while(g==1)
{
printf("Result = %f ",result);
printf("Input: ");
scanf("%c",&op);
if(op=='+')
{
scanf("%f",&input);
result += input;
printf("Output: Result + %f = %f ",input,result);
}
else if(op=='-')
{
scanf("%f",&input);
result -= input;
printf("Output: Result - %f = %f ",input,result);
}
else if(op=='*')
{
scanf("%f",&input);
result *= input;
printf("Output: Result * %f = %f ",input,result);
}
else if(op=='/')
{
scanf("%f",&input);
result /= input;
printf("Output: Result / %f = %f ",input,result);
}
else if(op=='r')
{
printf("Output: Final result = %f. Again? (y/n):",result);
scanf("%c",&tp);
if(tp=='n')
{
g=0;
}
}
else
{
printf("Ouput: %c is an unknown operation. Reenter, your last line ",op);
scanf("%f",&input);
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.