What is the most efficient way to create a floating point mode where the user can enter f
or i
to switch between integer and floating point? I d like to do this without having to copy the entire code for floats. I know typecasting is an option but I m not completely sure if it s the safest way.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
int *p;
int *tos;
int *bos;
void push(int i);
int pop(void);
int main (void)
{
int a, b;
char s[80];
p = (int *) malloc(MAX*sizeof(int)); /* get stack memory */
if (!p) {
printf("Allocation Failure
");
exit(1);
}
tos = p;
bos = p + MAX-1;
printf("
RPN Calculator
");
printf("Enter i for integer mode
");
printf("Enter f for floating point mode
");
printf("Enter q to quit
");
char *endptr;
do {
printf("> ");
scanf("%s", s);
int val = strtol(s, &endptr, 10);
if (*endptr == ) {
//printf("Got only the integer: %d
", val);
}
else {
printf("operator: %s
", endptr);
printf("integer: %d
", val);
if (val != 0){ /* don t push val on stack if 0 */
push(val);
}
}
switch(*endptr) {
case i :
printf("(Integer Mode)
");
break;
case f :
printf("(Floating Point Mode)
");
break;
case + :
a = pop();
b = pop();
// printf("%d
",a);
// printf("%d
",b);
// printf("%d
",val);
printf("%d
", a+b);
push(a+b);
break;
case - :
a = pop();
b = pop();
printf("%d
", b-a);
push(b-a);
break;
case * :
a = pop();
b = pop();
printf("%d
", a*b);
push(a*b);
break;
case / :
a = pop();
b = pop();
if(a == 0){
printf("Cannot divide by zero
");
break;
}
printf("%d
", b/a);
push(b/a);
break;
case . :
a = pop(); push(a);
printf("Current value on top of stack: %d
", a);
break;
default:
// push(atoi(s));
push(val);
}
} while (*s != q ); /* Do until q is entered */
return 0;
}
void push (int i) /* Put an element on the stack */
{
if (p > bos){
printf("Stack Full
");
return;
}
*p = i;
p++;
}
int pop (void) /* Get the element from the top of the stack */
{
p--;
if(p < 0) {
printf("Stack Underflow
");
return 0;
}
return *p;
}