|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STACKINCREAMENT 10
#define INIT_STACK_SIZE 20
#define MIXBUFFER 10
typedef char Elemtype;
typedef struct
{
Elemtype *base;
Elemtype *top;
int stackSize;
}sqstack;
// 初始化栈
void init_stack ( sqstack *s )
{
s->base = (Elemtype *) malloc (INIT_STACK_SIZE * sizeof(Elemtype));
if ( !s->base )
{
exit (0);
}
s->top = s->base;
s->stackSize = INIT_STACK_SIZE;
}
// 入栈操作
void push_stack ( sqstack *s, Elemtype i)
{
if ( s->top - s->base >= s->stackSize )
{
exit (0);
}
*(s->top) = i;
s->top++;
}
// 出栈操作
void pop_stack ( sqstack *s, double *i )
{
if ( s->top == s->base )
{
return ;
}
*i = *--(s->top);
}
// 主函数
int main ( void )
{
char i;
sqstack s;
double e, d ,sum;
char number[MIXBUFFER];
int n = 0;
init_stack ( &s );
printf ("输入公式,每个数以空格间隔,以#作为结束:\n"); // 输入公式的循环
scanf ("%c", &i);
while ( i != '#' )
{
while ( isdigit( i ) || i == '.') // 过滤作用
{
number[n++] = i;
number[n] = '\0'; //最后一个字符设置为0
if ( n >= MIXBUFFER )
{
printf ( "出错:输入的单个数据过大!\n" );
return -1;
}
scanf ( "%c", &i );
if ( i == ' ')
{
d = atof ( number );
push_stack ( &s, d );
n = 0;
break;
}
}
switch ( i )
{
case '+':
pop_stack ( &s, &e );
pop_stack ( &s, &d );
push_stack ( &s, e+d );
break;
case '-':
pop_stack ( &s, &e );
pop_stack ( &s, &d );
push_stack ( &s, d-e );
break;
case '*':
pop_stack ( &s, &e );
pop_stack ( &s, &d );
push_stack ( &s, e*d );
break;
case '/':
pop_stack ( &s, &e );
pop_stack ( &s, &d );
if ( e != 0 )
{
push_stack ( &s, d/e );
}
else
{
printf ("出错:除数为零!\n");
return -1;
}
break;
}
scanf ( "%c", &i );
}
pop_stack ( &s, &sum );
printf ("最终的计算结果为:%lf\n", sum);
system ("pause");
return 0;
}
正在小甲鱼的数据结构 逆波兰计算器 看完后自己动手了一下 可是为什么最后被四舍五入了 看了好久没找出来问题、、、
|
|