【问题标题】:wrong output from stack堆栈输出错误
【发布时间】:2019-10-28 08:57:03
【问题描述】:

输出为:100 100
应该是:9 100
我已经调用了两次push。当我调用print时,输出是错误的。

int main(){
    int i=9;
    Stackc s;
    s.push(i);
    i=100;
    s.push(i);
    s.print();
    return 0;
}

这是.h文件

class Stackc{
    int arr[100];
    int iTop;
public:
    int top();
    void push(int i);
    void pop();
    void print();
    Stackc();
};

这是构造函数

Stackc::Stackc(){
    iTop=-1;
    for(int i=0;i<100;i++)
        arr[i]=0;
}

这个函数将一个元素压入堆栈

void Stackc::push(int i){
    iTop++;
    arr[iTop]=i;
}

这是用于打印堆栈

void Stackc::print(){
    for(int i=0;i<=iTop;i++)
        cout<<arr[iTop]<<" ";
    cout<<endl;

}

【问题讨论】:

    标签: c++ data-structures stack


    【解决方案1】:

    这一行:

    cout << arr[iTop] << " ";
    

    应该是

    cout << arr[i] << " ";
    

    对于未来,我建议您查看How to create a Minimal, Reproducible Example。例如,一个最小的示例不需要跨越多个文件(除非问题是关于如何处理多个文件)。理想情况下,只需复制/粘贴一段代码即可运行代码,如下所示:

    class Stackc {
        int arr[100];
        int iTop;
    public:
        Stackc() {
            iTop = -1;
            for (int i = 0; i < 100; i++)
                arr[i] = 0;
        }
    
        void push(int i) {
            iTop++;
            arr[iTop] = i;
        }
    
        void print() {
            for (int i = 0; i <= iTop; i++)
                std::cout << arr[i] << " ";
            std::cout << std::endl;
    
        }
    
    };
    
    int main() {
        int i = 9;
        Stackc s;
        s.push(i);
        i = 100;
        s.push(i);
        s.print();
        return 0;
    }
    

    我还推荐以下问答:

    Why is "using namespace std;" considered bad practice?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-26
      • 2019-02-16
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多