Практика в использовании условной логики
На этом последнем этапе вы примените все, что вы узнали о структурах принятия решений в языке C, создав комплексную программу, которая демонстрирует несколько приемов условной логики.
Создадим многоцелевую программу с именем personal_finance_advisor.c
в директории ~/project
, которая поможет пользователям принимать финансовые решения:
cd ~/project
touch personal_finance_advisor.c
#include <stdio.h>
int main() {
double income, expenses, savings;
char employment_status, age_group;
// Input financial information
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);
// Calculate savings rate
double savings_rate = (savings / income) * 100;
double disposable_income = income - expenses;
// Financial advice using complex conditional logic
printf("\n--- Financial Analysis ---\n");
// Savings advice
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);
}
// Investment recommendations
if ((employment_status == 'F' && disposable_income > 500) ||
(age_group == 'Y' && savings > 5000)) {
printf("Recommendation: Consider starting an investment portfolio.\n");
}
// Emergency fund advice
if (savings < (expenses * 3)) {
printf("Advice: Build an emergency fund covering at least 3 months of expenses.\n");
}
// Spending control
if (expenses > (income * 0.7)) {
printf("Alert: Your expenses are too high compared to your income.\n");
}
// Special conditions
if ((age_group == 'Y' && employment_status == 'F') ||
(savings > (income * 2))) {
printf("You are in a good financial position!\n");
}
// Detailed financial health assessment
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);
// Calculate average
double average = (math_score + science_score + english_score) / 3.0;
// Comprehensive grade determination
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 для сложного принятия решений
- Учитывайте крайние случаи и предоставляйте комплексную логику
- Разбивайте сложные проблемы на более мелкие, управляемые условия