A shorter way to write following c++ code (if-else)

yas*_*han -1 c++ optimization logic if-statement

I need to know is there a better / shorter way to write following code in c++. (while going through the main if-else (step by step), additional check for variable 'y' will be added)

int x = 5, y = 4;        

if(x == 1){
  if(y == 1)
      printf("ok");
  else
      printf("not ok");
}
else if(x == 2){
  if((y == 1) || (y == 2))
      printf("ok");
  else
      printf("not ok");
}
else{
  if((y == 1) || (y == 2) || (y == 3))
      printf("ok");
  else
      printf("not ok");
}
Run Code Online (Sandbox Code Playgroud)

小智 6

if(0<y && y<4 && (y<=x || x<1))
    printf("ok");
else
    printf("not ok");
Run Code Online (Sandbox Code Playgroud)

@Christophe,您是对的,下面的解释可能会有所帮助:

int x = 5, y = 4;        

if(x == 1){
  if(y == 1)
      printf("ok");
  else
      printf("not ok");
}
else if(x == 2){
  if((y == 1) || (y == 2))
      printf("ok");
  else
      printf("not ok");
}
else{
  if((y == 1) || (y == 2) || (y == 3))
      printf("ok");
  else
      printf("not ok");
}
Run Code Online (Sandbox Code Playgroud)

当'printf(“ ok”);' 被执行,'(y == 1)|| (y == 2)|| (y == 3)'必须为'true'。

“ x”和“ y”是整数表示:

'(y == 1)|| (y == 2)|| (y == 3)'等价于'0 <y && y <4',因为当'y'是其中的一个{1,2,3,4 ,.时,'0 <y'为'true'。 。}和'y <4'为'true',而'y'是其中之一{3,2,1,0,-1,-2,...}和'0 <y && y <4'是'true'表示:'y'是其中的一个{1,2,3}。

当你写:

if(0<y && y<4)
    printf("ok");
else
    printf("not ok");
Run Code Online (Sandbox Code Playgroud)

如果您进入此分支,将会有太多的“确定”:

if(x == 1){
  ...
}
Run Code Online (Sandbox Code Playgroud)

或成这样:

else if(x == 2){
  ...
}
Run Code Online (Sandbox Code Playgroud)

当您进入两个分支之一时,两个分支中的“ 1 <= x”为“ true”。

这意味着:如果'x <1'(相当于'!(1 <= x)')为'true',则您不会陷入其中之一。

当你写:

if(0<y && y<4 && x<1)
    printf("ok");
else
    printf("not ok");
Run Code Online (Sandbox Code Playgroud)

如果'x'是其中的一个{1,2,3,4,5,...}并且'y'是正确的,那么就会有太多的“不好”。

  1. 'x'为1:'0'y && y <4'对于'ok'必须为'true',但是'x <1'将为'false'!。
  2. 'x'是2:'0'y && y <4'对于'ok'必须为'true',但是'x <1'将为'false'!。
  3. 'x'为3或更大:'0'<y && y <4'对于'ok'必须为'true',但是'x <1'将为'false'!。

对于1和2。'0<y && y <4'太大(认为等价'y == 1 || y == 2 || y == 3'),但两者都为'true '和'x <1'为'false',但必须有类似'(... || x <1)'的内容,并且此'...'必须确保:

  1. “ y”为1,而“ x”为1且
  2. “ y”为1或“ y”为2,而“ x”为2且
  3. 当“ x”等于或大于3时,“ y”等于1或“ y”等于2或“ y”等于3。

对于1.'x'为1:'y <= 1'

对于2。'x'为2:'y <= 2'在两种情况下,'y <= x'都是正确的。

对于3。'x'为3或更大:'y <= x'始终为'true',当'y'是正确的('y == 1 || y == 2 || y == 3') 。

然后您得到答案。