#include <iostream>
using namespace std;
struct stack
{
int *stkarray;
int top;
int maxarray;
};
//khởi tạo stack rỗng
int initstk(stack &s, int max)
{
s.stkarray = new(int[max]);
if (s.stkarray == NULL)
return 0;
s.maxarray = max;
s.top = 0;
return 1;
}
bool isempty(stack s)
{
return (s.maxarray = 0);
}
bool isfull(stack s)
{
return (s.top > s.maxarray);
}
bool push(stack &s, int newitem)
{
if (isfull(s))
return false;
s.stkarray[s.top] = newitem;
s.top++;
return true;
}
bool pop(stack &s, int &outitem)
{
if (isempty(s))
return false;
s.top--;
outitem = s.stkarray[s.top];
return true;
}
void dec_to_x(stack s,int dec,int base)
{
bool thanhcong = true;
unsigned long
int temp = dec;
while (temp > 0 && (thanhcong))
{
if (isfull(s))
{
thanhcong = false;
cout << "/n STACK Day.";
}
else
{
push(s, temp % base);
}
temp = temp / base;
}
if (thanhcong)
{
cout << "ke qua chuyen so " << dec << " he thap phan sang he " << base << "la : ";
while (pop(s, dec))
{
if (dec >= 10)
{
cout << dec + 55;
}
else
{
cout << dec;
}
}
}
}
int main()
{
stack s;
int dec, base;
initstk(s, 100);
cout <<"Nhap so can chuyen doi :";
cin >> dec;
cout << "Nhap he so can chuyen";
cin >> base;
dec_to_x(s, dec, base);
return 0;
system("pause");
}
mọi người xem giùm sai ở đâu ạ?
Kiểm tra lại hàm isempty, pop
Ý nghĩa của stack.top hình như là lưu số ptu hơn là lưu chỉ số top?
cái hàm isempty trả về true. còn làm pop vẫn chưa biết sai ở đâu mong đc chỉ giáo
Ý nghĩa của stack.top trong cài đặt của bạn là lưu số phần tử nên hàm isempty() phải sửa thành:
bool isempty(const stack& s)
{
return (s.top == 0);
}
Trong hàm dec_to_x, trong TH cơ số lớn hơn 10 và dec >= 10 thì khi in ra kết quả phải là:
cout << (char) (dec - 10 + 'A');
1 Like
bool isempty(const stack& st){ return st.top==0;}
....
while(pop(st,x)){
cout<<"0123456789ABCDEF"[x];
}
2 Likes
Có thể dùng lớp stack trong thư viện STL của C++.
#include <iostream>
#include <stack>
using namespace std;
// Convert decimal number to a number in base @base
// Store results in the stack myStack
void convert(int dec, int base, stack<int>& myStack) {
int temp = dec;
int res;
while ( temp > 0 ) {
res = temp % base;
temp = temp / base;
myStack.push(res);
}
}
// Print output stored in the stack
void printOutput(stack<int>& myStack) {
while ( ! myStack.empty() ) {
int t = myStack.top();
cout << "0123456789ABCDEF"[t];
myStack.pop();
}
cout << endl;
}
int main() {
stack<int> myStack;
int dec, base;
cout << "Input decimal number: "; cin >> dec;
cout << "Input base to convert: "; cin >> base;
convert(dec, base, myStack);
printOutput(myStack);
return 0;
}
1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?