Click to See Complete Forum and Search --> : functions


codenewb
February 26th, 2003, 10:34 AM
When I'm using functions in code do I use them to replace my if
statements, I guess I'm just not certain where to put them.
I am supposed to change the code in this and add functions.

#include <stdio.h>

#define REGFEE 35.00
#define SURCHG 15.00
#define CITYV 20.00

main()
{
void GetCtype();
void GetVtype();
int vtype, ctype, custcount = 0;
char answer;
double totfee, totcustchg = 0.0;


do
{
int GetCtype();
printf("\nPlease enter a 1 for Luxury Car, or 2 for Other Car: ");
scanf("%d", &vtype);

if (!(vtype ==1 || vtype == 2))
{
printf("\nInvalid Data Entered: ");
}
else
{
int GetVtype();
printf("\nPlease enter a 1 for City Vehicle, or 2 for Non-City Vehicle: ");
scanf("%d", &ctype);
if (!(ctype ==1 || ctype ==2))
{
printf("\nInvalid Data Entered: ");
}
else
{

if ((vtype == 1) && (ctype ==1))
{
totfee = REGFEE + SURCHG + CITYV;
}
else
{
totfee = REGFEE + SURCHG;

if ((vtype ==2) && (ctype ==2))
{
totfee = REGFEE;
}
else
{
totfee = REGFEE + CITYV;
}
}
}
}

printf("\nTotal Fee %.2f\n", totfee);





//Accumulators
++custcount;
totcustchg += totfee;

//Prompt for another car
printf("\nDo you want to process another vehicle?(y/n): ");
getchar();
answer = getchar();
}
while (( answer == 'y') || (answer == 'Y') );

//Display summary info
printf("\nTotal number of cars processed: %d\n", custcount);
printf("\nTotal registration fee for all automobiles: $%.2lf\n", totcustchg);




}

kuphryn
February 26th, 2003, 02:20 PM
I recommend that you reread the chapter on function in your C++ book.

Kuphryn

wbartley
February 26th, 2003, 05:46 PM
One important purpose of functions is to make your code more readable and also easier to test. Isn't the following easier to read than the program you presented?

enum VehicleType { luxury, other };
enum VehicleUse {city, noncity };

VehicleType GetVehicleType()
{
// Code to get vehicle type from user
}

VehicleUse GetVehicleUse()
{
// Code to get vehicle use from user
}

int main(void)
{
do {
VehicleType vtype = GetVehicleType();
VehicleUse vuse = GetVehicleUse();
int totalFee = REGFEE;
if (vtype == luxury){
totalFee += SURCHG;
}
if (vuse == city){
totalFee += CITYV
}
// Compute your stats
} while (// more cars to process);
}

codenewb
February 26th, 2003, 08:25 PM
I see now, I was confused on how I would enter
the functions regarding the if statement. Your reply
made it a bit easier to comprehend, thanks.