习题五第三小题

1.要求:

设计算法,把十进制整数转换为二至九进制之间任意进制输出

 

2.思考:

十进制转换其他进制,即使用短除法,再取其余数,倒输出,因此可以使用后进先出的栈来编程。


3.程序

头文件:

#include <iostream>
using namespace std;
const int StackSize=100;
class Exchange
{
public:
 Exchange(){top=-1;}
 void change(int x,int y);
 void output();
 ~Exchange(){}
 void push(int x);
 int pop();
 int Empty(){top==-1?1:0;}
private:
 int data[StackSize];
 int top;
 
};


源文件:

#include "a.h"
#include <iostream>
using namespace std;
void Exchange::push(int x){
 if (top==StackSize-1)throw"Finish";
 data[++top]=x;
}

int Exchange::pop(){
 int x;
 if (top==-1)throw"Finish";
 x=data[top--];
 cout<<x;
 return 0;
}


void Exchange::change(int x,int y){
 int number=x;
 int rule=y;
 int result;
 result=number%rule;
 push(result);
 if(number/rule>=rule)
  change(number/rule,y);
 else
  push(number/rule);

}

void Exchange::output(){
  for(top;top!=-1; ){
  pop();}
}
int main(){
 Exchange x;
    x.change(10,9);
 x.output();
 return 0;
}

编译结果:

数字10转化为9进制:

数字100转换为2进制:

数字10转化为8进制:

由此实践可知,使用了顺序栈的编程能够正确运行,解决问题。





猜你喜欢

转载自blog.csdn.net/Lxin12138/article/details/78108293