简介
在本实验中,你将学习如何在 C 编程中构建决策结构。你将从理解 if
语句的基本概念开始,该语句允许你的程序根据特定条件做出决策。接着,你将探索不等运算符、链式 if-else
语句、使用逻辑运算符组合表达式,并练习条件逻辑。通过本实验的学习,你将掌握如何在 C 程序中创建决策结构,从而编写出更复杂和智能的代码。
在本实验中,你将学习如何在 C 编程中构建决策结构。你将从理解 if
语句的基本概念开始,该语句允许你的程序根据特定条件做出决策。接着,你将探索不等运算符、链式 if-else
语句、使用逻辑运算符组合表达式,并练习条件逻辑。通过本实验的学习,你将掌握如何在 C 程序中创建决策结构,从而编写出更复杂和智能的代码。
在本步骤中,你将学习 C 编程中 if
语句的基本概念,这对于在代码中创建决策结构至关重要。if
语句允许你的程序根据特定条件做出决策并执行不同的代码块。
让我们从一个简单的 C 程序开始,演示基本的 if
语句语法。打开 VSCode 编辑器,在 ~/project
目录下创建一个名为 if_statement.c
的新文件:
cd ~/project
touch if_statement.c
#include <stdio.h>
int main() {
int temperature = 25;
if (temperature > 30) {
printf("It's a hot day!\n");
}
if (temperature <= 30) {
printf("The temperature is comfortable.\n");
}
return 0;
}
编译并运行程序:
gcc if_statement.c -o if_statement
./if_statement
示例输出:
The temperature is comfortable.
让我们分解一下 if
语句:
if
关键字后跟一个用括号 ()
括起来的条件{}
内的代码块现在,让我们创建一个更具交互性的示例,展示 if
语句如何根据用户输入做出决策:
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are eligible to vote.\n");
}
if (age < 18) {
printf("You are not old enough to vote.\n");
}
return 0;
}
编译并运行程序:
gcc voting_eligibility.c -o voting_eligibility
./voting_eligibility
示例输出:
Enter your age: 20
You are eligible to vote.
需要记住的关键点:
if
语句允许你的程序做出决策>
、<
、>=
、<=
、==
、!=
在本步骤中,你将通过探索不等运算符深入学习 C 编程,这些运算符对于创建更复杂的条件语句至关重要。不等运算符允许你比较值并根据它们的关系做出决策。
让我们在 ~/project
目录下创建一个名为 inequality_operators.c
的新文件,以演示不同的不等运算符:
cd ~/project
touch inequality_operators.c
#include <stdio.h>
int main() {
int x = 10;
int y = 20;
// 等于 (==) 运算符
if (x == y) {
printf("x is equal to y\n");
} else {
printf("x is not equal to y\n");
}
// 不等于 (!=) 运算符
if (x != y) {
printf("x is different from y\n");
}
// 大于 (>) 运算符
if (y > x) {
printf("y is greater than x\n");
}
// 小于 (<) 运算符
if (x < y) {
printf("x is less than y\n");
}
// 大于或等于 (>=) 运算符
if (y >= x) {
printf("y is greater than or equal to x\n");
}
// 小于或等于 (<=) 运算符
if (x <= y) {
printf("x is less than or equal to y\n");
}
return 0;
}
编译并运行程序:
gcc inequality_operators.c -o inequality_operators
./inequality_operators
示例输出:
x is not equal to y
x is different from y
y is greater than x
x is less than y
y is greater than or equal to x
x is less than or equal to y
让我们创建另一个示例,展示如何使用不等运算符处理用户输入:
#include <stdio.h>
int main() {
int score;
printf("Enter your exam score: ");
scanf("%d", &score);
if (score >= 90) {
printf("Excellent! You got an A.\n");
} else if (score >= 80) {
printf("Good job! You got a B.\n");
} else if (score >= 70) {
printf("Not bad. You got a C.\n");
} else if (score >= 60) {
printf("You passed. You got a D.\n");
} else {
printf("Sorry, you failed the exam.\n");
}
return 0;
}
编译并运行程序:
gcc grade_calculator.c -o grade_calculator
./grade_calculator
示例输出:
Enter your exam score: 85
Good job! You got a B.
需要记住的关键点:
==
检查值是否相等!=
检查值是否不相等>
检查左侧值是否大于右侧值<
检查左侧值是否小于右侧值>=
检查左侧值是否大于或等于右侧值<=
检查左侧值是否小于或等于右侧值在本步骤中,你将学习如何通过链式 if-else
语句在 C 编程中创建更复杂的决策结构。链式 if-else
语句允许你处理多个条件,并在之前的条件未满足时提供替代的代码路径。
让我们在 ~/project
目录下创建一个名为 weather_advisor.c
的文件,以演示链式 if-else
语句:
cd ~/project
touch weather_advisor.c
#include <stdio.h>
int main() {
int temperature;
char weather_type;
printf("Enter the temperature: ");
scanf("%d", &temperature);
printf("Enter the weather type (S for sunny, R for rainy, C for cloudy): ");
scanf(" %c", &weather_type);
if (temperature > 30 && weather_type == 'S') {
printf("It's a hot and sunny day. Stay hydrated and use sunscreen!\n");
} else if (temperature > 30 && weather_type == 'R') {
printf("It's hot and rainy. Be careful of potential thunderstorms.\n");
} else if (temperature > 30 && weather_type == 'C') {
printf("It's hot and cloudy. Wear light clothing.\n");
} else if (temperature >= 20 && temperature <= 30) {
printf("The temperature is comfortable.\n");
} else if (temperature < 20) {
printf("It's a bit cool today. Consider wearing a light jacket.\n");
} else {
printf("Invalid input. Please check your temperature and weather type.\n");
}
return 0;
}
编译并运行程序:
gcc weather_advisor.c -o weather_advisor
./weather_advisor
示例输出:
Enter the temperature: 35
Enter the weather type (S for sunny, R for rainy, C for cloudy): S
It's a hot and sunny day. Stay hydrated and use sunscreen!
让我们创建另一个示例,展示链式 if-else
语句的更实际用途:
#include <stdio.h>
int main() {
char category;
double price, discount = 0.0;
printf("Enter product category (A/B/C): ");
scanf(" %c", &category);
printf("Enter product price: ");
scanf("%lf", &price);
if (category == 'A') {
if (price > 1000) {
discount = 0.2; // 20% discount for high-value A category
} else {
discount = 0.1; // 10% discount for A category
}
} else if (category == 'B') {
if (price > 500) {
discount = 0.15; // 15% discount for high-value B category
} else {
discount = 0.05; // 5% discount for B category
}
} else if (category == 'C') {
if (price > 200) {
discount = 0.1; // 10% discount for high-value C category
} else {
discount = 0.0; // No discount for low-value C category
}
} else {
printf("Invalid category!\n");
return 1;
}
double discounted_price = price * (1 - discount);
printf("Original price: $%.2f\n", price);
printf("Discount: %.0f%%\n", discount * 100);
printf("Discounted price: $%.2f\n", discounted_price);
return 0;
}
编译并运行程序:
gcc discount_calculator.c -o discount_calculator
./discount_calculator
示例输出:
Enter product category (A/B/C): B
Enter product price: 600
Original price: $600.00
Discount: 15%
Discounted price: $510.00
需要记住的关键点:
if-else
语句允许你处理多个条件else
块在没有条件满足时提供默认操作if-else
语句以创建更复杂的决策结构在本步骤中,你将学习如何在 C 编程中使用逻辑运算符组合多个条件。逻辑运算符允许你通过连接多个表达式来创建更复杂的条件语句。
让我们在 ~/project
目录下创建一个名为 logical_operators.c
的文件,以演示三种主要的逻辑运算符:AND (&&
)、OR (||
) 和 NOT (!
):
cd ~/project
touch logical_operators.c
#include <stdio.h>
int main() {
int age, income;
char is_student;
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your annual income: ");
scanf("%d", &income);
printf("Are you a student? (Y/N): ");
scanf(" %c", &is_student);
// AND (&&) 运算符:两个条件都必须为真
if (age >= 18 && income < 30000) {
printf("You qualify for a basic credit card.\n");
}
// OR (||) 运算符:至少一个条件必须为真
if (age < 25 || is_student == 'Y') {
printf("You may be eligible for a student discount.\n");
}
// 组合多个条件
if ((age >= 18 && income >= 30000) || (is_student == 'Y')) {
printf("You qualify for a premium credit card.\n");
}
// NOT (!) 运算符:否定条件
if (!(age < 18)) {
printf("You are an adult.\n");
}
return 0;
}
编译并运行程序:
gcc logical_operators.c -o logical_operators
./logical_operators
示例输出:
Enter your age: 22
Enter your annual income: 25000
Are you a student? (Y/N): Y
You qualify for a basic credit card.
You may be eligible for a student discount.
You qualify for a premium credit card.
You are an adult.
让我们创建另一个示例,展示更复杂的逻辑条件:
#include <stdio.h>
int main() {
char membership_type;
int visits_per_month, total_spending;
printf("Enter your membership type (B for Bronze, S for Silver, G for Gold): ");
scanf(" %c", &membership_type);
printf("Enter number of visits per month: ");
scanf("%d", &visits_per_month);
printf("Enter total monthly spending: ");
scanf("%d", &total_spending);
// 使用多个逻辑运算符的复杂条件
if ((membership_type == 'G') ||
(membership_type == 'S' && visits_per_month >= 10) ||
(membership_type == 'B' && total_spending > 500)) {
printf("You are eligible for a special promotion!\n");
}
// 使用 NOT 运算符的复杂条件
if (!(membership_type == 'B' && visits_per_month < 5)) {
printf("You can access additional membership benefits.\n");
}
return 0;
}
编译并运行程序:
gcc membership_conditions.c -o membership_conditions
./membership_conditions
示例输出:
Enter your membership type (B for Bronze, S for Silver, G for Gold): S
Enter number of visits per month: 12
Enter total monthly spending: 300
You are eligible for a special promotion!
You can access additional membership benefits.
需要记住的关键点:
&&
(AND) 运算符:两个条件都必须为真||
(OR) 运算符:至少一个条件必须为真!
(NOT) 运算符:否定条件在最后的步骤中,你将通过创建一个综合程序来应用所学的 C 语言决策结构知识,该程序将展示多种条件逻辑技术。
让我们在 ~/project
目录下创建一个名为 personal_finance_advisor.c
的多功能程序,帮助用户做出财务决策:
cd ~/project
touch personal_finance_advisor.c
#include <stdio.h>
int main() {
double income, expenses, savings;
char employment_status, age_group;
// 输入财务信息
printf("Enter your monthly income: $");
scanf("%lf", &income);
printf("Enter your monthly expenses: $");
scanf("%lf", &expenses);
printf("Enter your current savings: $");
scanf("%lf", &savings);
printf("Employment status (F for Full-time, P for Part-time, U for Unemployed): ");
scanf(" %c", &employment_status);
printf("Age group (Y for Young (18-35), M for Middle-aged (36-55), S for Senior (56+)): ");
scanf(" %c", &age_group);
// 计算储蓄率
double savings_rate = (savings / income) * 100;
double disposable_income = income - expenses;
// 使用复杂条件逻辑提供财务建议
printf("\n--- Financial Analysis ---\n");
// 储蓄建议
if (savings_rate < 10) {
printf("Warning: Your savings rate is low (%.2f%%).\n", savings_rate);
} else if (savings_rate >= 10 && savings_rate < 20) {
printf("Good start! Your savings rate is moderate (%.2f%%).\n", savings_rate);
} else {
printf("Excellent! Your savings rate is strong (%.2f%%).\n", savings_rate);
}
// 投资建议
if ((employment_status == 'F' && disposable_income > 500) ||
(age_group == 'Y' && savings > 5000)) {
printf("Recommendation: Consider starting an investment portfolio.\n");
}
// 应急基金建议
if (savings < (expenses * 3)) {
printf("Advice: Build an emergency fund covering at least 3 months of expenses.\n");
}
// 支出控制
if (expenses > (income * 0.7)) {
printf("Alert: Your expenses are too high compared to your income.\n");
}
// 特殊条件
if ((age_group == 'Y' && employment_status == 'F') ||
(savings > (income * 2))) {
printf("You are in a good financial position!\n");
}
// 详细的财务健康评估
if (!(disposable_income < 0)) {
printf("Your disposable income is: $%.2f\n", disposable_income);
} else {
printf("Warning: Your expenses exceed your income.\n");
}
return 0;
}
编译并运行程序:
gcc personal_finance_advisor.c -o personal_finance_advisor
./personal_finance_advisor
示例输出:
Enter your monthly income: $5000
Enter your monthly expenses: $3500
Enter your current savings: $10000
Employment status (F for Full-time, P for Part-time, U for Unemployed): F
Age group (Y for Young (18-35), M for Middle-aged (36-55), S for Senior (56+)): Y
--- Financial Analysis ---
Good start! Your savings rate is moderate (40.00%).
Recommendation: Consider starting an investment portfolio.
You are in a good financial position!
Your disposable income is: $1500.00
让我们创建一个额外的挑战程序,进一步练习条件逻辑:
#include <stdio.h>
int main() {
int math_score, science_score, english_score;
char extra_credit;
printf("Enter Math score (0-100): ");
scanf("%d", &math_score);
printf("Enter Science score (0-100): ");
scanf("%d", &science_score);
printf("Enter English score (0-100): ");
scanf("%d", &english_score);
printf("Did you complete extra credit? (Y/N): ");
scanf(" %c", &extra_credit);
// 计算平均分
double average = (math_score + science_score + english_score) / 3.0;
// 综合成绩评定
if (average >= 90 ||
(extra_credit == 'Y' && average >= 85)) {
printf("Congratulations! You earned an A grade.\n");
} else if (average >= 80 ||
(extra_credit == 'Y' && average >= 75)) {
printf("Great job! You earned a B grade.\n");
} else if (average >= 70 ||
(extra_credit == 'Y' && average >= 65)) {
printf("You passed. You earned a C grade.\n");
} else {
printf("You need to improve. Consider retaking the courses.\n");
}
return 0;
}
编译并运行程序:
gcc grade_calculator.c -o grade_calculator
./grade_calculator
示例输出:
Enter Math score (0-100): 85
Enter Science score (0-100): 88
Enter English score (0-100): 92
Did you complete extra credit? (Y/N): N
Great job! You earned a B grade.
需要记住的关键点:
if-else
语句进行复杂决策在本实验中,你学习了 C 编程中 if
语句的基本概念,这对于在代码中创建决策结构至关重要。你探索了 if
语句如何允许程序根据特定条件做出决策并执行不同的代码块。你还学习了不等运算符、链式 if-else
语句、使用逻辑运算符组合表达式,以及通过练习条件逻辑在 C 程序中构建更复杂的决策结构。
本实验涵盖的关键点包括理解 if
语句的基本语法、将逻辑表达式评估为真或假,以及根据条件执行适当的代码块。你还学习了如何使用 if
语句根据用户输入做出决策,这是构建交互式应用程序的重要技能。