- D 語言基礎
- D 語言 - 首頁
- D 語言 - 概述
- D 語言 - 環境配置
- D 語言 - 基本語法
- D 語言 - 變數
- D 語言 - 資料型別
- D 語言 - 列舉
- D 語言 - 字面量
- D 語言 - 運算子
- D 語言 - 迴圈
- D 語言 - 條件判斷
- D 語言 - 函式
- D 語言 - 字元
- D 語言 - 字串
- D 語言 - 陣列
- D 語言 - 關聯陣列
- D 語言 - 指標
- D 語言 - 元組
- D 語言 - 結構體
- D 語言 - 共用體
- D 語言 - 範圍
- D 語言 - 別名
- D 語言 - 混合宏
- D 語言 - 模組
- D 語言 - 模板
- D 語言 - 不可變物件
- D 語言 - 檔案 I/O
- D 語言 - 併發
- D 語言 - 異常處理
- D 語言 - 合約程式設計
- D 語言 - 條件編譯
- D 語言 - 面向物件
- D 語言 - 類與物件
- D 語言 - 繼承
- D 語言 - 過載
- D 語言 - 封裝
- D 語言 - 介面
- D 語言 - 抽象類
- D 語言 - 有用資源
- D 語言 - 快速指南
- D 語言 - 有用資源
- D 語言 - 討論
D 語言 if...else 語句
一個if語句可以後跟一個可選的else語句,當布林表示式為假時執行。
語法
D 程式語言中if...else語句的語法如下:
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
} else {
/* statement(s) will execute if the boolean expression is false */
}
如果布林表示式計算結果為true,則執行if 塊中的程式碼;否則,執行else 塊中的程式碼。
D 程式語言將任何非零和非空值視為true,如果值為零或空,則視為false值。
流程圖
示例
import std.stdio;
int main () {
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a < 20 ) {
/* if condition is true then print the following */
writefln("a is less than 20" );
} else {
/* if condition is false then print the following */
writefln("a is not less than 20" );
}
writefln("value of a is : %d", a);
return 0;
}
編譯並執行以上程式碼後,將產生以下結果:
a is not less than 20; value of a is : 100
if...else if...else 語句
一個if語句可以後跟一個可選的else if...else語句,這對於使用單個 if...else if 語句測試各種條件非常有用。
使用 if、else if、else 語句時,需要注意以下幾點:
一個if語句可以有零個或一個else語句,並且必須放在任何else if語句之後。
一個if語句可以有零個或多個else if語句,並且必須放在else語句之前。
一旦一個else if語句成功,就不會測試任何剩餘的else if語句或else語句。
語法
D 程式語言中if...else if...else語句的語法如下:
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
} else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* executes when the none of the above condition is true */
}
示例
import std.stdio;
int main () {
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a == 10 ) {
/* if condition is true then print the following */
writefln("Value of a is 10" );
} else if( a == 20 ) {
/* if else if condition is true */
writefln("Value of a is 20" );
} else if( a == 30 ) {
/* if else if condition is true */
writefln("Value of a is 30" );
} else {
/* if none of the conditions is true */
writefln("None of the values is matching" );
}
writefln("Exact value of a is: %d", a );
return 0;
}
編譯並執行以上程式碼後,將產生以下結果:
None of the values is matching Exact value of a is: 100
d_programming_decisions.htm
廣告