Exercise 3-4. Modify the last example in the chapter that implemented a calculator so
that the user is given the option to enter y or Y to carry out another calculation, and n or
N to end the program. (note: You’ll have to use a goto statement for this here, but you’ll
learn a better way of doing this in the next chapter.)
My:
1 #include<stdio.h> 2 int main() 3 { 4 double number1 = 0.0; 5 double number2 = 0.0; 6 char operation = 0; 7 8 start: 9 printf("/nEnter the calculation"); 10 scanf("%lf %c %lf", &number1, &operation, &number2); 11 12 switch(operation) 13 { 14 case '+': 15 printf("= %lf ",number1 + number2); 16 break; 17 case '-': 18 printf("%lf ", &number1 - &number2); 19 break; 20 case'*': 21 printf("%lf ", &number1 * &number2); 22 break; 23 case'/': 24 if(number2 == 0) //check the second operand for zero 25 printf(" a Division by zero erro "); 26 break; 27 else 28 printf("%lf ", &number / &number2); 29 break; 30 case'%': 31 if((long)number2 = 0;) 32 printf(" aDivision by zero erro "); 33 break; 34 else 35 printf("%lf ", (long)number1 % (long)number2); 36 break; 37 default: 38 printf(" aIllegal operation "); 39 break; 40 } 41 42 //The followoing statements added to prompt for continuing 43 char answer = 'n'; 44 printf(" Do you want to do another calculation?(y or n);"); 45 scanf("%c", &answer); 46 if(answer=='y'||answer == 'y'); 47 go to start; // go back to the beginning 48 49 return 0; 50 51 }
Original:
1 /*Exercise 3.4 A calculator that allows multiple calculations */ 2 #include <stdio.h> 3 4 int main(void) 5 { 6 double number1 = 0.0; /* First operand value a decimal number */ 7 double number2 = 0.0; /* Second operand value a decimal number */ 8 char operation = 0; /* Operation - must be +, -, *, /, or % */ 9 start: 10 printf(" Enter the calculation "); 11 scanf("%lf %c %lf", &number1, &operation, &number2); 12 13 switch(operation) 14 { 15 case '+': // No checks necessary for add 16 printf("= %lf ", number1 + number2); 17 break; 18 19 case '-': // No checks necessary for subtract 20 printf("= %lf ", number1 - number2); 21 break; 22 23 case '*': // No checks necessary for multiply 24 printf("= %lf ", number1 * number2); 25 break; 26 27 case '/': 28 if(number2 == 0) // Check second operand for zero 29 printf(" aDivision by zero error! "); 30 else 31 printf("= %lf ", number1 / number2); 32 break; 33 34 case '%': // Check second operand for zero 35 if((long)number2 == 0) 36 printf(" aDivision by zero error! "); 37 else 38 printf("= %ld ", (long)number1 % (long)number2); 39 break; 40 41 default: // Operation is invalid if we get to here 42 printf(" aIllegal operation! "); 43 break; 44 } 45 46 /* The following statements added to prompt for continuing */ 47 char answer = 'n'; 48 printf(" Do you want to do another calculation? (y or n): "); 49 scanf(" %c", &answer); 50 if(answer == 'y' || answer == 'Y') 51 goto start; /* Go back to the beginning */ 52 53 return 0; 54 }