D
Darklight
why does the program below using swtich function add the last
value enter when exitting the program snip below:
while(choice != 'q'){
printf("Total %.2f\n",result);
variable();
switch(choice){
case 'q':
value = 0;
/* this is to stop last value being add when exiting program*/
puts("exiting program");
case '+':
result += value; break;
case '-':
result -= value; break;
case '*':
result *= value; break;
case '/':
if(value == 0){
printf("Error value == 0\n");
printf("Value ignored\n");
}
else
result /= value; break;
default:
printf("Incorrect operator try again\n"); break;
}
}
printf("Total = %.2f\n",result);
return 0;
}
but if i use if & else to do the same thing
it gives the correct output
while(1) {
printf("result: %.2f\n",result);
variable();
if (( operator == 'q' || operator == 'Q')) /*to quite program */
break;
if(operator == '+') {
result += value;
} else if (operator == '-') {
result -= value;
} else if (operator == '*') {
result *= value;
} else if (operator == '/') {
if (value == 0) {
printf("Errorivide by zero\n"); /*prints error if number = 0 */
printf(" operation ignored\n");
} else
result /= value;
} else {
printf("Unknown Operator %c\n", operator);
}
}
printf("result: %.2f\n",result);
return(0);
}
value enter when exitting the program snip below:
while(choice != 'q'){
printf("Total %.2f\n",result);
variable();
switch(choice){
case 'q':
value = 0;
/* this is to stop last value being add when exiting program*/
puts("exiting program");
case '+':
result += value; break;
case '-':
result -= value; break;
case '*':
result *= value; break;
case '/':
if(value == 0){
printf("Error value == 0\n");
printf("Value ignored\n");
}
else
result /= value; break;
default:
printf("Incorrect operator try again\n"); break;
}
}
printf("Total = %.2f\n",result);
return 0;
}
but if i use if & else to do the same thing
it gives the correct output
while(1) {
printf("result: %.2f\n",result);
variable();
if (( operator == 'q' || operator == 'Q')) /*to quite program */
break;
if(operator == '+') {
result += value;
} else if (operator == '-') {
result -= value;
} else if (operator == '*') {
result *= value;
} else if (operator == '/') {
if (value == 0) {
printf("Errorivide by zero\n"); /*prints error if number = 0 */
printf(" operation ignored\n");
} else
result /= value;
} else {
printf("Unknown Operator %c\n", operator);
}
}
printf("result: %.2f\n",result);
return(0);
}