Saturday, May 9, 2009

C++…….......?

How would the following program look if it had a function to do the calculation?





Would I use a void function or no?

C++…….......?
You'd probably use double, not void because you want to return the fuel consumption. Your program needs a bit more work because you have not converted litres to gallons, or indeed declared litres, or indeed calculated anything sensible.





litres*miles that you and pugyking used is not a useful unit except in hyperdimensional space so forget that calculation.





double mpg(double litres, double miles)


{


return miles/(litres*0.22); // imperial NOT US gallons


}





....


milesPerGallon = mpg(totalGasoline, totalMiles);
Reply:You would just have a function called something like mpl so you would have:





double mpl(double miles, double liters)


{


double milesPerLiter = liters* miles;


return milesPerLiter ;


}





The call from main would be:


double milesPerLiter = mpl(miles, liters);





A few points worth mentioning.


1. This calculation is a one liner and using a function for it seems wasteful.





2. You are mixing SI and US units, this should be avoided (use kilometers per liter or miles per gallon rather than miles per liter).





3. Don't call the calculated value miles per gallon since it's actually miles per liter (unless of course you follow the advice above).


No comments:

Post a Comment