经营者评价

Mat*_*zak 1 c++ operators

此代码的计算结果为true:

#include <iostream>


int main(){
 int x = 9;
 int j = x-1;

 if(x - j+1 > 1)
  std::cout << "Ehhhh???\n";
}
Run Code Online (Sandbox Code Playgroud)

但这一个是假的:

#include <iostream>

int main(){
 int x = 9;
 int j = x-1;

 if(x - (j+1) > 1)
  std::cout << "Ehhhh???\n";
}
Run Code Online (Sandbox Code Playgroud)

加号和减号运算符的优先级高于"<",我也只使用一种数据类型,因此应该有bo溢出.为什么结果不同?

Nat*_*ica 7

这实际上只是1加入的值.加法和减法有从左到右的相关性,所以我们从左边开始,按照我们的方式正确行事.

x - j + 1
(9 - 8) + 1
1 + 1
2
Run Code Online (Sandbox Code Playgroud)

在哪里

x - (j + 1)
9 - (8 + 1)
9 - 9
0
Run Code Online (Sandbox Code Playgroud)

强制附加附加j而不是x-j第二种情况是正确的.


Bir*_*ebe 6

由于算术+和 - 的优先级相同但关联性是从左到右,没有括号的那个将首先进行减法然后加法,即:

x - j+1 ==2 //here the operation is performed from left to right,subtraction first then addition
x - (j+1)==0 //here the one inside the parenthesis will be done first,i.e addition first then subtraction
Run Code Online (Sandbox Code Playgroud)