本文概述
- 如果其他
- 如果不是, 则去链
- 嵌套if-else
句法 :
if(boolean_expression) {
/* statement(s) got executed only if the expression results in true */
}
如果例子去
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
/* check the boolean condition using if statement */
if( a % 2==0 ) {/* if condition is true then print the following
*/ fmt.Printf("a is even number" )
}
}
输出:
a is even number
如果其他if-else用于测试条件。如果条件为真, 则执行块, 否则执行块。
句法 :
if(boolean_expression) {
/* statement(s) got executed only if the expression results in true */
} else {
/* statement(s) got executed only if the expression results in false */
}
转到if-else示例
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10;
/* check the boolean condition */
if ( a%2 == 0 ) {
/* if condition is true then print the following */
fmt.Printf("a is even\n");
} else {
/* if condition is false then print the following */
fmt.Printf("a is odd\n");
}
fmt.Printf("value of a is : %d\n", a);
}
输出:
a is even
value of a is : 10
Go If-else示例:用户输入
func main() {
fmt.Print("Enter number: ")
var input int
fmt.Scanln(&
input)
fmt.Print(input)
/* check the boolean condition */
if( input % 2==0 ) {
/* if condition is true then print the following */
fmt.Printf(" is even\n" );
} else {
/* if condition is false then print the following */
fmt.Printf(" is odd\n" );
}
}
输出:
Enter number: 10
10 is even
如果不是, 则去链Go if else-if链用于从多个条件执行一个语句。
我们可以有N个if-else语句。没有限制。
【Go if-else语句】大括号{}在if-else语句中是必需的, 即使其中只有一条语句也是如此。 else-if和else关键字必须在右花括号}之后位于同一行。
如果为if-if链, 则转到示例
package main
import "fmt"
func main() {
fmt.Print("Enter text: ")
var input int
fmt.Scanln(&
input)
if (input <
0 || input >
100) {
fmt.Print("Please enter valid no")
} else if (input >
= 0 &
&
input <
50) {
fmt.Print(" Fail")
} else if (input >
= 50 &
&
input <
60) {
fmt.Print(" D Grade")
} else if (input >
= 60 &
&
input <
70) {
fmt.Print(" C Grade")
} else if (input >
= 70 &
&
input <
80) {
fmt.Print(" B Grade")
} else if (input >
= 80 &
&
input <
90) {
fmt.Print(" A Grade")
} else if (input >
= 90 &
&
input <
= 100) {
fmt.Print(" A+ Grade")
}
}
输出:
Enter text: 84
A Grade
嵌套if-else我们还可以嵌套if-else语句以从多个条件执行一个语句。
句法
if( boolean_expression 1) {
/* statement(s) got executed only if the expression 1 results in true */
if(boolean_expression 2) {
/* statement(s) got executed only if the expression 2 results in true */
}
}
嵌套if-else示例
package main
import "fmt"
func main() {
/* local variable definition */
var x int = 10
var y int = 20
/* check the boolean condition */
if( x >
=10 ) {
/* if condition is true then check the following */
if( y >
= 10 ){
/* if condition is true then print the following */
fmt.Printf("Inside nested If Statement \n" );
}
}
fmt.Printf("Value of x is : %d\n", x );
fmt.Printf("Value of y is : %d\n", y );
}
输出:
Inside nested If Statement
Value of x is : 10
Value of y is : 20