Subj : Re: C++ functionality To : borland.public.cpp.borlandcpp From : maeder Date : Wed May 25 2005 10:57 pm "ron Hopkins" writes: Your immediate question has already been answered. Let me point out some points about your program: > // Travel Efficiency > // > // Purpose: Calculates miles per gallon and price per mile when > // given miles traveled, number of gallons used, and gas price. > > #include // necessary for cin and cout commands > > int main() > { > // Variable declarations > float MilesTraveled; // stores number of miles > float GallonsUsed; // stores number of total gallons used > float PricePerGallon; // stores price per gallon > float PricePerMile; // stores price per mile > float MilesPerGallon; // stores number of miles per gallon This is just my personal opinion, and I'm sure there are people who will disagree with me here. But the comments after these variable definitions should not be there. Either the variables are correctly named, which means that the comments are superfluous. Or the variables are incorrectly named - then their names should be fixed in a way that makes the comments superfluous. I am not against judicious comments, like documenting what a function does, what the parameter values are expected to be, or why something is done the way it is. But if a piece of information can be put into compiled code, this is always to be prefered. > // Ask user for input values. > cout << "How many miles did you travel? "; > cin >> MilesTraveled; > cout << "How many gallons of gas did you use? "; > cin >> GallonsUsed; > cout << "How much did one gallon of gas cost? $"; > cin >> PricePerGallon; All these input operations can fail, leaving the float variables unintialized. > // Divide the number of miles by the number of gallons to get MPG. > MilesPerGallon = MilesTraveled / GallonsUsed; Reading an unitialized variable has undefined behavior. As in "anything can happen, including the computer catching fire." And we haven't talked about non-positive inputs yet ... Better do something like int main() { // Ask user for input values. cout << "How many miles did you travel? "; float MilesTraveled; if (cin >> MilesTraveled && MilesTraveled>0) { cout << "How many gallons of gas did you use? "; float GallonsUsed; if (cin >> GallonsUsed && GallonsUsed>0) { cout << "How much did one gallon of gas cost? $"; float PricePerGallon; if (cin >> PricePerGallon && PricePerGallon>=0) { float MilesPerGallon = MilesTraveled / GallonsUsed; float PricePerMile = PricePerGallon / MilesPerGallon; cout << "You got " << MilesPerGallon << " miles per gallon,\n"; cout << "and each mile cost $" << PricePerMile << "\n"; return EXIT_SUCCESS; } } } cerr << "Input failure\n"; return EXIT_FAILURE; } .