Programming in C

(Barry) #1

82 Chapter 6 Making Decisions


operator with blank spaces when you type in these values. If you had specified the for-
mat string "%f%c%f"instead, no spaces would have been permitted after typing in the
first number and before typing in the operator.This is because when the scanffunction
is reading a character with the %cformat characters, the next character on the input,even
if it is a blank space, is the character that is read. However, it should be noted that, in gen-
eral, the scanffunction alwaysignores leading spaces when it is reading in either a deci-
mal or floating-point number.Therefore, the format string "%f %c%f"would have
worked just as well in the preceding program.
After the second operand has been keyed in and stored in the variable value2, the
program proceeds to test the value of operatoragainst the four permissible operators.
When a correct match is made, the corresponding printfstatement is executed to dis-
play the results of the calculation. Execution of the program is then complete.
A few words about program thoroughness are in order at this point.While the pre-
ceding program does accomplish the task that it was set to perform, the program is not
really complete because it does not account for mistakes made by the user. For example,
what happens if the user types in a ?for the operator by mistake? The program simply
“falls through” the ifstatement and no messages ever appear at the terminal to alert the
user that he incorrectly typed in his expression.
Another case that is overlooked is when the user types in a division operation with
zero as the divisor.You know by now that you should never attempt to divide a number
by zero in C.The program should check for this case.
Tr ying to predict the ways that a program can fail or produce unwanted results and
then taking preventive measures to account for such situations is a necessary part of pro-
ducing good, reliable programs. Running a sufficient number of test cases against a pro-
gram often points the finger to portions of the program that do not account for certain
cases. But it goes further than that. It must become a matter of self-discipline while cod-
ing a program to always say “What would happen if ...” and to insert the necessary pro-
gram statements to handle the situation properly.
Program 6.8A, a modified version of Program 6.8, accounts for division by zero and
the keying in of an unknown operator.

Program 6.8A Revising the Program to Evaluate Simple Expressions
/* Program to evaluate simple expressions of the form
value operator value */

#include <stdio.h>

int main (void)
{
float value1, value2;
char operator;

printf ("Type in your expression.\n");
scanf ("%f %c %f", &value1, &operator, &value2);
Free download pdf