tailieunhanh - Using if Statements to Make Decisions

Báo cáo sử dụng nếu để Thực hiện Quyết định Bạn sử dụng một tuyên bố nếu khi bạn muốn lựa chọn giữa hai khối thi khác nhau của mã tùy thuộc vào kết quả của một biểu thức Boolean. | Using if Statements to Make Decisions You use an if statement when you want to choose between executing two different blocks of code depending on the result of a Boolean expression. Understanding if Statement Syntax The syntax of an if statement is as follows if and else are keywords if booleanExpression statement-1 else statement-2 If booleanExpression evaluates to true then statement-1 runs otherwise booleanExpression is false and statement-2 runs. The else keyword and the following statement-2 are optional. If there is no else clause nothing happens when the booleanExpression is false. For example here s an if statement that increments the seconds hand of a stopwatch minutes are ignored for now . If the value of the seconds variable is 59 it is reset to 0 otherwise it is incremented using the operator int seconds . if seconds 59 seconds 0 else seconds Boolean Expressions Only Please The expression in an if statement must be enclosed in parentheses. Additionally the expression must be a Boolean expression. In some other languages notably C and C you can write an integer expression and the compiler will silently convert the integer value to true nonzero or false zero . C does not support this behavior and the compiler reports an error if you write such an expression. If you accidentally write an assignment instead of an equality test in an if statement the C compiler recognizes your mistake. For example int seconds if seconds 59 compile-time error if seconds 59 ok Accidental assignments were another common source of bugs in C and C programs which would silently convert the value assigned 59 into a Boolean expression anything non-zero was considered to be true with the result that the code following the if statement would be performed every time. Finally you can use a Boolean variable as the expression as in this example bool inWord . if inWord true ok but not commonly used if inWord better Using Blocks to Group Statements Sometimes you ll want to run two or more .