怎样用C语言实现不同数据类型入同一个栈???

来源:百度知道 编辑:UC知道 时间:2024/05/17 06:15:41
我的入栈只能是同一个数据类型,比如只能是整型、浮点型--,如果是两个同时输入的话就不行了,请问这个问题怎么解决???

由于浮点数和整数存储方法的不同,浮点数到整数的转换存在精度的问题,计算机是无法用浮点数精确地表示整数的,像整数3,表示成浮点数值可能成为2.9999999999,这也就是浮点数之间比较相等必须要计算上误差的存在。

你可以写一个像这样的结构:

typedef enum ElemType_TAG {FLOAT, INTEGER} ElemType;

typedef struct Elem_TAG {
ElemType type;
union Value {
float fvalue;
int ivalue;
} value;
} Elem;

然后栈的类型改成 Elem 就可以了,不喜欢联合,可以换成void *,不过效率应该会低一些。

typedef struct _tokentype{
int token_value_int;
float token_value_float;
}toketype;
toketype stack_of_opnd[20];//栈
int sp_opnd = -1;//栈指针
向上面一样浪费点内存,就可以存储了。

或者在你的栈中只存指针,如:

void* stack[1000];//栈
int sp=-1;

push()
{
int * buff1 = malloc(sizeof(int));
float *buff2 = malloc(sizeof(float));
stack[++sp]=buff1;
stack[++sp]=buff2;
//
}

只要使用union就可以不浪费内存,float32位,ulong32位,INT32也是32位,char8位,搂住可以这样写
struct stackelement
{