I'm writing a program to calculate the miles per gallon that a vehicle delivers. The user inputs the liters consumed and the miles that the car traveled, and then a function calculates the miles per gallon.
I'm wondering which of the following functions would be better programming form: creating a new variable or using a compound math statement. I know for something this simple it probably doesn't matter, but I want to go ahead and get into good habits. So if this were a more complicated program that I was doing professionally, which of these should I use?
*note: LITERS_PER_GALLON is a globally defined const, because that's what the question in my book wanted me to do.
Here is the function using a compound math statement (no new variable):
1 2 3 4
|
double milesPerGallon (double litersConsumed, double milesTraveled)
{
return (milesTraveled / (litersConsumed * LITERS_PER_GALLON));
}
|
This version seems like it would save on resources. Why create a new variable if you don't actually need it, right?
Here is the function using a new variable:
1 2 3 4 5 6 7
|
double milesPerGallon (double litersConsumed, double milesTraveled)
{
double gallons;
gallons = litersConsumed * LITERS_PER_GALLON;
return (milesTraveled / gallons);
}
|
This version seems like it would make the function easier to understand for other programmers.
Thanks for any tips you guys can provide on this.