ubuntu vim里编写的逆波兰表示法计算器程序 运行出现以下问题 求教
出现的问题是 + - * / 运行正确,但是sin cos pow 等运行结果出错,比如:3.14159265 2 / sin 的结果不是1, 2 3 pow 的结果不是8, 求大神,前辈指点,谢谢!程序: calculator.c(主程序)+ popandpush.c + getop.c +getchandungetch.c + mathfnc.c
如下:
/*逆波兰计算器*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAXOP 100
#define NUMBER '0'
#define NAME 'n'
int getop(char []);
void push(double);
double pop(void);
void mathfnc(char s[]);
main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF){
switch (type){
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error:zero divisor\n");
break;
case NAME:
mathfnc(s);
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("error:unknown command %s\n", s);
break;
}
}
return 0;
}
---------------------------------------
/*popandpush.c*/
#define MAXVAL 100
#include <stdio.h>
int sp = 0;
double val[MAXVAL];
void push(double f)
{
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error:stack full, can't push %g\n", f);
}
double pop(void)
{
if(sp > 0)
return val[--sp];
else{
printf("error:stack empty\n");
return 0.0;
}
}
------------------------------
/*getop.c*/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define NUMBER '0'
#define NAME 'n'
int getch(void);
void ungetch(int);
int getop(char s[])
{
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
i = 0;
if (islower(c)){
while (islower(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
if (strlen(s) > 1)
return NAME;
else
return c;
}
if (!isdigit(c) && c != '.')
return c;
if (isdigit(c))
while (isdigit(s[++i] = c = getch()))
;
if(c == '.')
while (isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
-------------------------------
/*getchandungetch.c*/
#define BUFSIZE 100
#include <stdio.h>
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch:too many characers\n");
else
buf[bufp++] = c;
}
---------------------------
/*mathfnc.c*/
#include <stdio.h>
#include <string.h>
#include <math.h>
void mathfnc(char s[])
{
double op2;
if (strcmp(s, "sin") == 0)
push(sin(pop()));
else if (strcmp(s, "cos") == 0)
push(cos(pop()));
else if (strcmp(s, "exp") == 0)
push(exp(pop()));
else if (strcmp(s, "pow") == 0){
op2 = pop();
push(pow(op2, pop()));
}
else
printf("error: %s is not supported\n", s);
}
[ 本帖最后由 lobsters 于 2013-3-15 16:51 编辑 ]