I'm learning to code with Deitel's C: How to program book, 6th edition. Here's Exercise 5.9 (Parking Charges):
A parking garage charges a $2.00 minimum fee to park for up to three hours and an additional $0.50 per hour for each hour or part thereof over three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time. Write a program that will calculate and print the parking charges for each of three customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format, and should calculate and print the total of yesterday's receipts. The program should use the function calculateCharges to determine the charge for each customer.
My solution is below. These exercises have no answers so I don't know how can I improve this code, in which I want to know if it is possible to dispense with variables "one", "two" and "three", and also automate the printing process (after the for loop in main) inside a loop.
#include <stdio.h>
float calculateCharges( float hours );
float charge;
int main()
{
int customer;
float one;
float two;
float three = 0;
float hours;
for( customer = 1; customer <= 3; customer++ ) {
printf( "Enter customer #%d parking hours: ", customer );
scanf( "%f", &hours );
if( customer == 1 )
one = hours;
else if( customer == 2 )
two = hours;
else
three = hours;
}
printf( "%s%10s%12s", "Car", "Hours", "Cost" );
printf( "\n%d%12.1f%12.1f", 1, one, calculateCharges( one ) );
printf( "\n%d%12.1f%12.1f", 2, two, calculateCharges( two ) );
printf( "\n%d%12.1f%12.1f", 3, three, calculateCharges( three ) );
printf( "\n%s%8.1f%12.1f", "TOTAL", one + two + three, calculateCharges( one ) + calculateCharges( two ) + calculateCharges( three ) );
}
float calculateCharges( float hours )
{
int h = hours;
charge = 2.0;
if( hours > 0 ) {
if( hours <= 3 )
return charge;
else if( hours <= 24 ) {
while( h > 3 ) {
charge += .5;
h--;
if( charge >= 10 )
charge = 10;
}
return charge;
}
}
else
printf( "\nThe amount of time entered is not supported." );
}