if语句后面可以跟随可选的else语句,该语句在布尔表达式为false时执行。
D编程语言中if.else语句的语法是-
if(boolean_expression) { /* 如果布尔表达式为真(true),则语句将执行 */ } else { /* 如果布尔表达式为假(false),语句将执行 */ }
如果布尔表达式的计算结果为true,则执行代码的if块,否则执行代码的else块。
d编程语言将任何非零和非NULL值假定为TRUE,如果它是零或NULL,则假定它为FALSE值。
import std.stdio; int main () { /* 局部变量定义 */ int a=100; /* 检查布尔条件 */ if( a < 20 ) { /* 如果条件为真,则打印以下内容 */ writefln("a is less than 20" ); } else { /* 如果条件为假,则打印以下内容 */ writefln("a is not less than 20" ); } writefln("value of a is : %d", a); return 0; }
编译并执行上述代码时,将生成以下结果-
链接:https://www.learnfk.comhttps://www.learnfk.com/d-programming/d-programming-if-else-statement.html
来源:LearnFk无涯教程网
a is not less than 20; value of a is : 100
If语句后面可以跟随可选的Else If.Else语句,这对于使用单个If.Else If语句测试各种条件非常有用。
在使用If,Else语句时,有几点需要牢记-
if可以有零个或一个其他IF,并且它必须在任何其他IF之后。
if可以有零到许多其他if,它们必须出现在else之前。
一旦Else If成功,就不会测试其余的Else If或Else。
D编程语言中if.else语句的语法是-
if(boolean_expression 1) { /* 当布尔表达式 1 为真时执行 */ } else if( boolean_expression 2) { /* 当布尔表达式 2 为真时执行 */ } else if( boolean_expression 3) { /* 当布尔表达式 3 为真时执行 */ } else { /* 当上述条件都不为真时执行 */ }
import std.stdio; int main () { /* 局部变量定义 */ int a=100; /* 检查布尔条件 */ if( a == 10 ) { /* 如果条件为真,则打印以下内容 */ writefln("Value of a is 10" ); } else if( a == 20 ) { /* if else if 条件为真 */ writefln("Value of a is 20" ); } else if( a == 30 ) { /* if else if 条件为真 */ writefln("Value of a is 30" ); } else { /* 如果没有一个条件为真 */ writefln("None of the values is matching" ); } writefln("Exact value of a is: %d", a ); return 0; }
编译并执行上述代码时,将生成以下结果-
链接:https://www.learnfk.comhttps://www.learnfk.com/d-programming/d-programming-if-else-statement.html
来源:LearnFk无涯教程网
None of the values is matching Exact value of a is: 100
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)