Print the Evaluated Result
In this final step, you will enhance the piecewise function program to provide more detailed output and demonstrate the function's behavior across different input ranges.
Let's modify the piecewise_function.c
file to add more comprehensive result printing:
cd ~/project
nano piecewise_function.c
Update the code with the following implementation:
#include <stdio.h>
// Define a piecewise function
double piecewise_function(double x) {
// Condition 1: If x is less than 0
if (x < 0) {
return x * x; // f(x) = x^2 for x < 0
}
// Condition 2: If x is between 0 and 5
else if (x >= 0 && x < 5) {
return 2 * x + 3; // f(x) = 2x + 3 for 0 ≤ x < 5
}
// Condition 3: If x is greater than or equal to 5
else {
return x - 2; // f(x) = x - 2 for x ≥ 5
}
}
int main() {
double x;
// Prompt the user to enter a value for x
printf("Piecewise Function Evaluator\n");
printf("Function rules:\n");
printf(" f(x) = x^2 for x < 0\n");
printf(" f(x) = 2x + 3 for 0 ≤ x < 5\n");
printf(" f(x) = x - 2 for x ≥ 5\n\n");
printf("Enter a value for x: ");
// Read the input value
scanf("%lf", &x);
// Calculate the result of the piecewise function
double result = piecewise_function(x);
// Provide detailed output
printf("\nInput Analysis:\n");
printf(" Input value x: %.2f\n", x);
// Determine and print the applied formula
if (x < 0) {
printf(" Applied formula: f(x) = x^2\n");
}
else if (x >= 0 && x < 5) {
printf(" Applied formula: f(x) = 2x + 3\n");
}
else {
printf(" Applied formula: f(x) = x - 2\n");
}
// Print the final result
printf(" Result f(x): %.2f\n", result);
return 0;
}
Compile the program:
gcc piecewise_function.c -o piecewise_function
Run the program with different input values:
./piecewise_function
Example output 1 (x < 0):
Piecewise Function Evaluator
Function rules:
f(x) = x^2 for x < 0
f(x) = 2x + 3 for 0 ≤ x < 5
f(x) = x - 2 for x ≥ 5
Enter a value for x: -3
Input Analysis:
Input value x: -3.00
Applied formula: f(x) = x^2
Result f(x): 9.00
Example output 2 (0 ≤ x < 5):
Piecewise Function Evaluator
Function rules:
f(x) = x^2 for x < 0
f(x) = 2x + 3 for 0 ≤ x < 5
f(x) = x - 2 for x ≥ 5
Enter a value for x: 3
Input Analysis:
Input value x: 3.00
Applied formula: f(x) = 2x + 3
Result f(x): 9.00
Example output 3 (x ≥ 5):
Piecewise Function Evaluator
Function rules:
f(x) = x^2 for x < 0
f(x) = 2x + 3 for 0 ≤ x < 5
f(x) = x - 2 for x ≥ 5
Enter a value for x: 6
Input Analysis:
Input value x: 6.00
Applied formula: f(x) = x - 2
Result f(x): 4.00
Key improvements in this step:
- Added detailed function rules explanation
- Provided input analysis with the applied formula
- Enhanced output readability
- Demonstrated the piecewise function behavior across different input ranges