New variable or compound math statement

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.
Last edited on
It does not actually matters. Both are fine. I would use second probably but write it like that:
1
2
3
4
5
6
double milesPerGallon (double litersConsumed, double milesTraveled)
{
    //↓Initialize variable as soon as it is declared.
    double gallonsConsumed = litersConsumed / LITERS_PER_GALLON;
    return milesTraveled / gallonsConsumed ;
}
That code is self documented which might be useful when you have more complex equations

Also please note that you should divide liters on LITERS_PER_GALLON (or multiply it on GALLONS_PER_LITER) to get gallons
Last edited on
Topic archived. No new replies allowed.