Programming in C

(Barry) #1
The ifStatement 81

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

if ( operator == '+' )
printf ("%.2f\n", value1 + value2);
else if ( operator == '-' )
printf ("%.2f\n", value1 - value2);
else if ( operator == '*' )
printf ("%.2f\n", value1 * value2);
else if ( operator == '/' )
printf ("%.2f\n", value1 / value2);

return 0;
}


Program 6.8 Output


Type in your expression.
123.5 + 59.3
182.80


Program 6.8 Output (Rerun)


Type in your expression.
198.7 / 26
7.64


Program 6.8 Output (Second Rerun)


Type in your expression.
89.3 * 2.5
223.25


The scanfcall specifies that three values are to be read into the variables value1,
operator,and value2.A floating value can be read in with the %fformat characters, the
same characters used for the output of floating values.This is the format used to read in
the value of the variable value1,which is the first operand of your expression.
Next, you want to read in the operator. Because the operator is a character ('+','-',
'*', or '/') and not a number, you read it into the character variable operator.The %c
format characters tell the system to read in the next character from the terminal.The
blank spaces inside the format string indicate that an arbitrary number of blank spaces
are to be permitted on the input.This enables you to separate the operands from the


Program 6.8 Continued
Free download pdf