1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <stdio.h>
//define constants
#define LITRES_PER_GALLON 3.785
#define KM_PER_MILE 1.609
//prototypes
float getInput(char*, float, float);
void main()
{
//declare variables
float distance, price, efficiency, cost;
//GET user input
distance = getInput("Enter the distance in miles: ", 0, 99999);
price = getInput("Enter the price of gas in $ per gallon: ", 0, 99999);
efficiency = getInput("Enter the efficiency rating in miles per gallon: ", 0, 99999);
//CALCULATE the cost based on the user data
cost = (distance / efficiency) * price * (LITRES_PER_GALLON / KM_PER_MILE);
//DISPLAY calculated cost
printf("The cost of the trip is $%.2f\n", cost);
//WAIT for user confirmation before ending program
system("pause");
}
float getInput(char* prompt, float lowerLim, float upperLim)
{
float input;
int check = 0;
while (check == 0)
{
//PROMPT the user
printf("%s", prompt);
//READ the input value
scanf_s("%f", &input);
//CHECK the input value if
if (input < lowerLim || input > upperLim)
{
printf("Error: Input is out of range. Please enter a value between %.2f and %.2f\n", lowerLim, upperLim);
}
else
{
//modify data check variable to indicate value is OK
check = 1;
}
}
return input;
}
| |