#include <iostream>
using namespace std;
class stack {
private:
int maxsize;
int top;
int* st2;
public:
~stack()
{
delete[]st2;
}
stack(int size)
{
maxsize = size;
st2 = new int[maxsize];
top = -1;
}
void push(int num)
{
st2[++top] = num;
}
void pop()
{
int item;
while (top != -1) {
item = st2[top--];
cout << item;
}
}
};
/*
TODO:設計演算法把一個十進制整數轉換為二至九進制之間的任意進制數輸出。
其中,n為要轉換的10進制整數, m為進制,取值為2到9。
提示:利用堆疊解決
*/
void Binaryconv(int n, int m) //進制轉換
{
stack s(32);
int a = n, b = 0;
while (a > 0)
{
a = n;
b = a % m;
a = a / m;
s.push(b);
}
cout << "整數" << n << "轉成" << m << "進制后的結果是:";
s.pop();
}
int main()
{
int n, m;
cin >> n;
cin >> m;
Binaryconv(n, m);
return 0;
}

uj5u.com熱心網友回復:
while (a > 0){
a = n;
b = a % m;
a = a / m;
s.push(b);
}
n不變
則a不變
則a/m不變
則死回圈
則無限push
則越界
則引發例外
uj5u.com熱心網友回復:
哦 漏了m不變uj5u.com熱心網友回復:
while (a > 0)
{
a = n; //這條陳述句為什么要在這里賦值,在while外已經賦值了。因為n沒有做修改,因此每次a都會被賦值初始值,這樣就會導致死回圈。
b = a % m;
a = a / m;
s.push(b);
}
uj5u.com熱心網友回復:
糊涂了,謝謝大佬
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/183371.html
標籤:C語言
