|
-
February 26th, 2003, 11:34 AM
#1
functions
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.
Code:
#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);
}
-
February 26th, 2003, 03:20 PM
#2
I recommend that you reread the chapter on function in your C++ book.
Kuphryn
-
February 26th, 2003, 06:46 PM
#3
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);
}
-
February 26th, 2003, 09:25 PM
#4
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|