0

これは非常に単純な質問のように思えるかもしれませんが、私はかなり混乱しています。多くの条件を含む if 条件があり、この場合に使用する括弧の構文がわかりません。この場合、または if ステートメントに多くの条件がある他の場合の適切な構文を理解する方法について、誰かヒントを教えてもらえますか? ありがとう!

  void collisionEn() {
    for (int i = 0; i < myPlats.length; i++) {
      if (posEx > myPlats[i].xPos) 
        && (posEx+wEx > myPlats[i].xPos) 
          && (posEx+wEx < myPlats[i].xPos + myPlats[i].platWidth)  
            && (posEx < myPlats[i].xPos + myPlats[i].platWidth)
              && (posEy > myPlats[i].yPos) 
                && (posEy < myPlats[i].yPos + myPlats[i].platHeight) 
                  && (posEy+wEy > myPlats[i]yPos) 
                    && (posEy+wEy < myPlats[i].yPos + myPlats[i].platHeight)
                      rect(0, 0, 1000, 1000);
4

2 に答える 2

1

各条件を括弧で囲む必要はありません (ただし、許可されています)。各条件を括弧で囲んでいますが、それで問題ありません。

ただし、条件全体を 1 組の括弧で囲む必要があります。

if (condition)

したがって、あなたの場合、最初に開き括弧を追加し、最後に閉じ括弧を追加すると、それが得られます。

  if ((posEx > myPlats[i].xPos) 
    && (posEx+wEx > myPlats[i].xPos) 
      && (posEx+wEx < myPlats[i].xPos + myPlats[i].platWidth)  
        && (posEx < myPlats[i].xPos + myPlats[i].platWidth)
          && (posEy > myPlats[i].yPos) 
            && (posEy < myPlats[i].yPos + myPlats[i].platHeight) 
              && (posEy+wEy > myPlats[i]yPos) 
                && (posEy+wEy < myPlats[i].yPos + myPlats[i].platHeight))
                  rect(0, 0, 1000, 1000)

かっこがたくさんあるという理由だけで、スタイル ガイドで許可されている場合は、各条件の周りの省略可能な括弧を削除することをお勧めします。それらは必要ではなく、この場合は混乱を招きます。

  if (posEx > myPlats[i].xPos
    && posEx+wEx > myPlats[i].xPos
    && posEx+wEx < myPlats[i].xPos + myPlats[i].platWidth
    && posEx < myPlats[i].xPos + myPlats[i].platWidth
    && posEy > myPlats[i].yPos
    && posEy < myPlats[i].yPos + myPlats[i].platHeight
    && posEy+wEy > myPlats[i]yPos
    && posEy+wEy < myPlats[i].yPos + myPlats[i].platHeight)
      rect(0, 0, 1000, 1000);
于 2013-04-22T12:00:23.310 に答える
0

コードをよりシンプルに保つために私が行うもう 1 つのことは、テストする計算を一時的に表すローカル var をいくつか用意することです。たとえば、テスト領域にマージンを追加したい場合は、次のように 1 か所で簡単に実行できます。

 float mpX = myPlats[i].xPos;
 float mpY = myPlats[i].yPos;
 float mpW = mpX + myPlats[i].platWidth;
 float mpH = mpY + myPlats[i].platHeight
 float pEx = posEx+wEx;
 float pEy = posEy+wEy;

 if (  posEx > mpX   &&   pEx > mpX
    &&   pEx < mpW   && posEx < mpW
    && posEy > mpY   && posEy < mpH
    &&   pEy > mpY   &&   pEy < mpH)
 rect(0, 0, 1000, 1000);

括弧については、他の計算と同じように if() で機能するため、演算子の優先順位に注意する必要がありますが、if ステートメント内で必要になることは一般的ではありません。しかし...時々、特に &&, ! 間の優先順位がそうです。と || 注意が必要です

于 2013-04-22T15:44:33.497 に答える