[prog] Learning C Question
Gretchen Dziengel
gdziengel at gmail.com
Sun Oct 30 11:45:26 EST 2005
I'm starting to work my way through a C book I picked up a while ago.
One of the first programs I'm working on is of course giving me
trouble.
printf( "Enter hours for customer one.\n" );
scanf( "%lf\n", &hours1 );
printf( "Enter hours for customer two.\n" );
scanf( "%lf\n", &hours2 );
printf( "Enter hours for customer three.\n" );
scanf( "%lf\n", &hours3 );
The first scanf wants me to put in two lines. Everything is then
offset by one. The second value I put in for hours1 turns into hours2
and the value for hours2 is stored as hours3. Whatever I put in for
hrours3 is gone.
I've quoted the entire program below because I've compared those lines
several thousand times and just don't get if they are different.
Also, I know this program could be much more effective with an array,
but I'm not quite there yet.
Thanks!
Gretchen
I compile with
gcc -g -lm -o 5-09 ex5-09.c
/****************************************
Exercise 5.9 Page 187
A parking garage charges a $2.00 minimum fee to park for up to three
hours. The garage charges an additional $0.50 per hour for each hour
or part thereof in excess of 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 3 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.
****************************************/
#include <stdio.h>
#include <math.h>
double calculateCharges( double );
int main ()
{
double hours1 = 0, hours2 = 0, hours3 = 0;
double charges1 = 0, charges2 = 0, charges3 = 0;
printf( "Enter hours for customer one.\n" );
scanf( "%lf\n", &hours1 );
printf( "Enter hours for customer two.\n" );
scanf( "%lf\n", &hours2 );
printf( "Enter hours for customer three.\n" );
scanf( "%lf\n", &hours3 );
charges1 = calculateCharges( hours1 );
charges2 = calculateCharges( hours2 );
charges3 = calculateCharges( hours3 );
printf( "Car\tHours\tCharges\n" );
printf( "1 \t %.1f \t %.2f \n", hours1, charges1 );
printf( "2 \t %.1f \t %.2f \n", hours2, charges2 );
printf( "3 \t %.1f \t %.2f \n", hours3, charges3 );
return 0;
}
double calculateCharges( double hours )
{
double charge = 0;
double totCharge = 0;
if ( hours <= 3 )
charge = 2;
if ( hours > 3 )
charge = 2.5;
totCharge = floor(hours) * charge;
if (totCharge > 10)
totCharge = 10;
return totCharge;
}
More information about the Programming
mailing list