If(条件判断语句) 和 比较运算符:修訂版本之間的差異

出自YFRobotwiki
跳轉到: 導覽搜尋
(以“if,它与比较运算符一起使用,用于判断条件是否满足,如一个输入值是否大于指定值。if语句语法格式: <pre style="color:dimgray...”为内容创建页面)
(沒有差異)

2015年6月4日 (四) 17:16的修訂版本

if,它與比較運算符一起使用,用於判斷條件是否滿足,如一個輸入值是否大於指定值。if語句語法格式:

if (someVariable > 50)
{
  // 在此添加执行代码
}

上面的程序為判斷someVariable 是否大於50。如果大於,執行指定代碼。換句話說,如果if後圓括號中的語句為真,則執行大括號中的代碼。反之,則跳過大括號中的代碼。

if語句後的大括號可以省略。如果這樣寫,下一行的語句(以分號結尾)將是唯一條件語句

if (x > 120) digitalWrite(LEDpin, HIGH); 

if (x > 120)
digitalWrite(LEDpin, HIGH); 

if (x > 120){ digitalWrite(LEDpin, HIGH); } 

if (x > 120){ 
  digitalWrite(LEDpin1, HIGH);
  digitalWrite(LEDpin2, HIGH); 
}                                 // 以上几种书写方式都正确

在圓括號中的語句需要使用一個或多個運算符:

比較運算符:

 x == y (x is equal to y)
 x != y (x is not equal to y)
 x <  y (x is less than y)  
 x >  y (x is greater than y) 
 x <= y (x is less than or equal to y) 
 x >= y (x is greater than or equal to y)

警告:

謹防誤使用單等號(例如if(x = 10))。單等號是賦值運算符,是用來設置x的值為10(將值10存入變量x中)。使用雙等號(例如if(x == 10)),這是比較運算符,用來測試x是否等於10。後者只有當x等於10時為真,而前者總是真。

這是因為C語言中 該語句if(x=10)是這樣執行的:10被賦值給了x(記住單等號是賦值運算符) This is because C evaluates the statement if (x=10) as follows: 10 is assigned to x (remember that the single equal sign is the assignment operator), so x now contains 10. Then the 'if' conditional evaluates 10, which always evaluates to TRUE, since any non-zero number evaluates to TRUE. Consequently, if (x = 10) will always evaluate to TRUE, which is not the desired result when using an 'if' statement. Additionally, the variable x will be set to 10, which is also not a desired action.

if can also be part of a branching control structure using the if...else construction.


返回Arduino語法參考列表

原文出處:Arduino官網

更多建議和問題歡迎反饋至 YFRobot論壇