"The C Programming Language", 2nd edition, Kernighan and Ritchie
Answer to Exercise 4-3, page 79
Given the basic framework, it's straightforward to extend the
calculator. Add the modulus (
% ) operator and provisions for negative
In Bob's words:
"Here's my attempt
Adding the modulus is easily done by another case in main and using
the fmod function. The standard library has been mentioned at this
point so it should be valid to use this for type 0 compliance.
math.h should be added to the list of #includes for fmod."
int flag = TRUE;
while((type = Getop(s)) != EOF)
/* other cases snipped for brevity */
op2 = pop();
printf("\nError: Division by zero!");
Bob goes on to say: "Deal with unary minus when retrieving tokens. This is based on the fact
that a unary minus will have no intervening space between it and its operand."
/* Getop: get next operator or numeric operand. */
int Getop(char s)
#define PERIOD '.'
int i = 0;
/* Skip whitespace */
while((s = c = getch()) == ' ' || c == '\t')
s = '\0';
/* Not a number but may contain a unary minus. */
if(!isdigit(c) && c != PERIOD && c != '-')
if(c == '-')
next = getch();
if(!isdigit(next) && next != PERIOD)
c = next;
c = getch();
while(isdigit(s[++i] = c))
c = getch();
if(c == PERIOD) /* Collect fraction part. */
while(isdigit(s[++i] = c = getch()))
s[i] = '\0';
if(c != EOF)
Back to index
You are visitor number - call again soon!