3

假设我希望返回tos = tos-2,那么如何修改代码?

int pop() {
    System.out.print("tos   = " +tos+"  ");
    if (tos<0) {
        System.out.println("Stack limit reached .. UNDERFLOW");
        return 0;}
    else {
        return stck[tos--]; 
    }
}
4

5 回答 5

2

Java 没有一元“减二”运算符,因此您必须将其拆分为两行:

tos -= 2;
return stck[tos + 2];

或者使用临时值来提高可读性:

tos -= 2;
int returnIndex = tos + 2;
return stck[returnIndex];
于 2014-12-12T10:04:48.857 回答
1

如果您想在更改之前返回数组位置tos(类似于return stck[tos--]会做的事情):

tos-=2;
return stck[tos+2];

除此以外,

tos-=2;
return stck[tos];
于 2014-12-12T10:05:25.173 回答
0
int pop(){
    System.out.print("tos   = " +tos+"  ");
    if (tos<0) {
        System.out.println("Stack limit reached .. UNDERFLOW");
        return 0;
    }
    else {
        tos = tos-2;
        return stck[tos];
    }
}
于 2014-12-12T10:05:01.097 回答
0
int pop(){

    System.out.print("tos   = " +tos+"  ");
    if (tos<0) {
        System.out.println("Stack limit reached .. UNDERFLOW");
        return 0;
    }
    else {
        tos -=2;
        return stck[tos];
    }
}
于 2014-12-12T10:36:31.227 回答
0

停止使用后缀。:D

int pop() {
        int tos = 2;//3

        System.out.print("tos   = " + tos + "  ");
        if (tos < 0) {
            System.out.println("Stack limit reached .. UNDERFLOW");
            return 0;
        } 

        return stck[tos-=2];
    }
于 2014-12-12T10:50:10.923 回答