我认为这段代码的结果= 4950.那是因为99 + 98 + ... 1 = 4950.你能告诉我怎么样吗?
public static void main(String[] args) {
int n = 100;
int total = 0;
while(n >= 0){
total += --n;
}
System.out.println(total);
}
Run Code Online (Sandbox Code Playgroud)
nic*_*ild 13
你是对的,99 + 98 + ... + 1 = 4950.但你必须遵循逻辑.
考虑当n = 0时.while循环的条件求值为true,并且在添加之前应用递减运算符total.如果递减值为0的变量,则得到-1,当你将-1加到4950时,得到4949.
所以我们真正看到的是:99 + 98 + ... + 1 + 0 +( - 1).这相当于4949.