Print Present Value
In this step, you will enhance the present value calculation program by adding formatted output and error handling to improve user experience.
Update the present_value.c
file with improved formatting and validation:
nano ~/project/present_value.c
Modify the code to include better output formatting:
#include <stdio.h>
#include <math.h>
int main() {
double future_value, rate, time, present_value;
// Input validation
printf("Present Value Calculator\n");
printf("----------------------\n");
printf("Enter Future Value (must be positive): ");
if (scanf("%lf", &future_value) != 1 || future_value <= 0) {
printf("Error: Invalid future value. Please enter a positive number.\n");
return 1;
}
printf("Enter Annual Interest Rate (in decimal, e.g., 0.05 for 5%%): ");
if (scanf("%lf", &rate) != 1 || rate < 0) {
printf("Error: Invalid interest rate. Please enter a non-negative number.\n");
return 1;
}
printf("Enter Time Period (in years, must be positive): ");
if (scanf("%lf", &time) != 1 || time <= 0) {
printf("Error: Invalid time period. Please enter a positive number.\n");
return 1;
}
// Calculate Present Value
present_value = future_value / pow((1 + rate), time);
// Formatted output
printf("\n--- Present Value Calculation ---\n");
printf("Future Value: $%.2f\n", future_value);
printf("Annual Rate: %.2f%%\n", rate * 100);
printf("Time Period: %.2f years\n", time);
printf("Present Value: $%.2f\n", present_value);
return 0;
}
Compile and run the updated program:
gcc -o present_value present_value.c -lm
./present_value
Example output:
Present Value Calculator
----------------------
Enter Future Value (must be positive): 1000
Enter Annual Interest Rate (in decimal, e.g., 0.05 for 5%): 0.05
Enter Time Period (in years, must be positive): 3
--- Present Value Calculation ---
Future Value: $1000.00
Annual Rate: 5.00%
Time Period: 3.00 years
Present Value: $862.07
Key improvements:
- Added input validation to prevent invalid inputs
- Enhanced output formatting with clear labels
- Improved error handling for user inputs
- Added descriptive prompts and calculation summary