How to use if statement to handle multiple conditions in C language?
In C language, we often need to make different processing according to different situations. Using if statements can help us achieve this goal, and when multiple conditions need to be processed, it can be accomplished by combining if-else statements or nested if statements. The following will introduce how to use if statements to handle multiple conditions in C language, and give specific code examples.
(1) Use if-else statements to process multiple conditions
The if-else statement executes a code block when a certain condition is met, otherwise it executes another code block. Nested if-else statements can be used when multiple conditions need to be processed.
#include <stdio.h> int main() { int score; printf("请输入考试成绩:"); scanf("%d", &score); if (score >= 90) { printf("优秀 "); } else if (score >= 80) { printf("良好 "); } else if (score >= 70) { printf("中等 "); } else if (score >= 60) { printf("及格 "); } else { printf("不及格 "); } return 0; }
In the above code example, different evaluations are output according to different score ranges.
(2) Use logical operators to process multiple conditions
In addition to nested if-else statements, we can also use logical operators to process multiple conditions.
#include <stdio.h> int main() { int num1, num2; printf("请输入两个数:"); scanf("%d %d", &num1, &num2); if (num1 > 0 && num2 > 0) { printf("两个数均大于0 "); } else if (num1 > 0 || num2 > 0) { printf("至少有一个数大于0 "); } else { printf("两个数都不大于0 "); } return 0; }
In the above code example, we use the logical operators && and || to handle the relationship between num1 and num2.
Through the above two methods, we can flexibly use if statements in C language to process multiple conditions, and choose the appropriate method to implement program logic according to the specific situation.
The above is the detailed content of How to handle multiple conditions using if statement in C language?. For more information, please follow other related articles on the PHP Chinese website!