灰色小妖 发表于 2014-8-13 22:15:34

用栈结构把二进制转换八进制的问题


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#definestack_int_size 20
#definestack_add_size 10
typedef char elemtype;//warning!!!
typedef struct{
    elemtype *base;
    elemtype *top;
    int topsize;
}node,* pnode;
void initializer_list(pnode s){         //初始化一个栈 大小为topstack
    s->base=(elemtype *)malloc(stack_int_size*sizeof(elemtype));
    if(!s->base){
      exit(0);
    }
    s->top=s->base;
    s->topsize=stack_int_size;
}
void push(pnode s,elemtype e){
    if((s->top)-(s->base)>=s->topsize){
      s->base=(elemtype *)realloc(s->base,(s->topsize+stack_add_size)*sizeof(elemtype));
      if(!(s->base)){
            exit(0);
      }
      }
      *(s->top)=e;
      s->top++;
    }
int pop(elemtype *e,pnode s){
    if(s->top==s->base){
      return 0;
    }
    *e=*--(s->top);
}
int stacklenth(pnode s){
    return (s->top-s->base);
}
int main()
{
    char c;
    int len,number,i,test,intnumber,j,total;
    j=total=0;
    number=0;
    pnode p=(pnode)malloc(sizeof(node));
    initializer_list(p);
    printf("请输入进制数:\n");
    printf("ended by #\n");
    scanf("%c",&c);
      while(c!='#'){
            push(p,c);
            scanf("%c",&c);
      }
      getchar();
      len=stacklenth(p);
      printf("栈当前容量是%d.\n",len);
      while(len>0){
      for(i=0;i<3;i++){
            test=pop(&c,p);
            --len;
            if(test==0){
                break;
            }
            number=number+(c-48)*pow(2,i);
      }
      printf("the number is %d.\n",number);
      total=total+number*pow(10,j);                      //关键问题出在这一行 看到我看到我看到我
      ++j;
      number=0;
   printf("the total number is %d.\n",total);
      }

    printf("the last number is %d.\n",total);
    return 0;
    }



===============================================================================
前方代码,在code blocks可运行
写的是将一个二进制数输入 以#键结束 然后转换成八进制数打印出来
问题出在一旦二进制数六位或者六位以上,最后的八进制数打印出来总会少1,
例如:输入110110110#会输出665实际应该是666
输入的二进制数在六位以下输出正确
经过调试
如果输入110110110#
前面都对
总是在    total=total+number*pow(10,j);      这一行 莫名其妙的就蹦成665
然后输出
百思不得其解
求!耐!心!人!看!一!看!好!么!
谢谢!


Mikel 发表于 2014-8-14 18:59:57

为什么要用栈呢?

灰色小妖 发表于 2014-8-17 05:43:48

Mikel 发表于 2014-8-14 18:59
为什么要用栈呢?

因为是按到数据结构的视频写的

灰色小妖 发表于 2014-8-20 22:03:45

自己停了几天又看
是因为pow()函数的出错
pow( )百度发现里面两个参数应该是double型
而返回值也是double型
所以改成double型后
答案就没出错了
页: [1]
查看完整版本: 用栈结构把二进制转换八进制的问题