为什么加起来等于11,而不等于8?

时间:2018-11-15 05:54:28

标签: java if-statement

我明天正在研究Intro comp sci测试,需要能够确定不同操作的价值。根据我的计算,t应该等于8。但是在编译时返回11。为什么要运行第二个if? 2不大于3。我知道这可能只是一个误解性问题,但确实可以解决。 提前致谢。

public class Prac {     
    public static void main(String []args){
        int i=4, j=3, k=10;
        float r=3, s=2, t=5;
        boolean done = false;

        if (s*2 >= j && t >= s) {
            if (s>j)
                s++;
            t = t * s;
        } else
            t += s;
        t++;
        System.out.println(t);
    }
}

1 个答案:

答案 0 :(得分:2)

外部条件为true,内部条件为false。

因此执行的语句为:

t = t * s; // 5 * 2 == 10

t++; // 11

使用适当的缩进和花括号将使代码更清晰:

    if (s*2 >= j && t >= s) { // 2 * 2 >= 3 && 5 >= 2 - true
        if (s>j) { // 2 > 3 - false
            s++; // not executed
        }
        t = t * s; // executed
    } else {
        t += s; // not executed
    }
    t++; // executed