Exercise 3-4. Modify The last example in the chapter then implemented a calculator so
That the user was given the option to enter Y or Y to carry out another calculation, and N or
N to end of the program. (Note:you ' ll has a goto statement for this
Learn a better the doing this in the next chapter.)
My:
1#include <stdio.h>2 intMain ()3 {4 DoubleNumber1 =0.0;5 DoubleNumber2 =0.0;6 CharOperation =0;7 8 Start:9printf"/nenter The calculation");Tenscanf"%lf%c%lf", &number1, &operation, &number2); One A Switch(Operation) - { - Case '+': theprintf"=%lf\n", Number1 +number2); - Break; - Case '-': -printf"%lf\n", &number1-&number2); + Break; - Case'*': +printf"%lf\n", &number1 * &number2); A Break; at Case'/': - if(Number2 = =0)//Check the second operand for zero -printf"\n\n\a division by Zero Erro\n"); - Break; - Else -printf"%lf\n", &number/&number2); in Break; - Case'%': to if((Long) Number2 =0;) +printf"\n\n\adivision by Zero erro\n"); - Break; the Else *printf"%lf\n", (Long) Number1% (Long) number2); $ Break;Panax Notoginseng default: -printf"\n\n\aillegal operation\n"); the Break; + } A the //The followoing statements added to prompt for continuing + CharAnswer ='N'; -printf"\ Want to do another calculation? (Y or n);"); $scanf"%c", &answer); $ if(answer=='y'|| Answer = ='y'); -Go to start;//go back to the beginning - the return 0; - Wuyi}
Original:
1 /*Exercise 3.4 A calculator that allows multiple calculations*/2#include <stdio.h>3 4 intMainvoid)5 {6 DoubleNumber1 =0.0;/*First operand value a decimal number*/7 DoubleNumber2 =0.0;/*Second operand value a decimal number*/8 CharOperation =0;/*operation-must be +,-, *,/, or%*/9 Start:Tenprintf"\nenter the calculation\n"); Onescanf"%lf%c%lf", &number1, &operation, &number2); A - Switch(Operation) - { the Case '+'://No checks necessary for add -printf"=%lf\n", Number1 +number2); - Break; - + Case '-'://No checks necessary for subtract -printf"=%lf\n", Number1-number2); + Break; A at Case '*'://No checks necessary for multiply -printf"=%lf\n", Number1 *number2); - Break; - - Case '/': - if(Number2 = =0)//Check second operand for zero inprintf"\n\n\adivision by Zero error!\n"); - Else toprintf"=%lf\n", Number1/number2); + Break; - the Case '%'://Check second operand for zero * if((Long) Number2 = =0) $printf"\n\n\adivision by Zero error!\n");Panax Notoginseng Else -printf"=%ld\n", (Long) Number1% (Long) number2); the Break; + A default://operation is invalid if we get to here theprintf"\n\n\aillegal operation!\n"); + Break; - } $ $ /*The following statements added to prompt for continuing*/ - CharAnswer ='N'; -printf"\ Want to do another calculation? (Y or N):"); thescanf"%c", &answer); - if(Answer = ='y'|| Answer = ='Y')Wuyi GotoStart/*Go back to the beginning*/ the - return 0; Wu}
Exercise 3.4 A Calculator that allows multiple calculations