Large numbers power of 10 Is there a way make the code better so that it does not have repeated code?

int totalDistance;

if (totalDistance &lt; pow(10, 3)) {
    cout &lt;&lt; "\nTotal (approx) travel distance = " &lt;&lt; totalDistance &lt;&lt; " million km\n" &lt;&lt; endl;
}
else if (totalDistance &lt; pow(10, 6)) {
    totalDistance = totalDistance / pow(10, 3);
    cout &lt;&lt; "\nTotal (approx) travel distance = " &lt;&lt; totalDistance &lt;&lt; " billion km\n" &lt;&lt; endl;
}
else if (totalDistance &lt; pow(10, 9)) {
    totalDistance = totalDistance / pow(10, 6);
    cout &lt;&lt; "\nTotal (approx) travel distance = " &lt;&lt; totalDistance &lt;&lt; " trillion km\n" &lt;&lt; endl;
}


totalDistance is measured in km and minimum distance is million. My main concern is when totalDistance has reached 1,000 or 1,000,000 then instead "million" change to "billion" or "trillion".
Step 1 is always to try it without the duplicated code and see what it might look like; then you can try to fill in the blanks to make the program compile again. So:

cout &lt;&lt; "\nTotal (approx) travel distance = "
     &lt;&lt; english_approximation(totalDistance) &lt;&lt; " km\n" &lt;&lt; endl;


And then you just have to write

std::string english_approximation(long long totalDistance)
{
    if (totalDistance &lt; 1e3) {
        return std::to_string(totalDistance) + " million";
    } else if (totalDistance &lt; 1e6) {
        return std::to_string(totalDistance / 1e3) + " billion";
    } else if (totalDistance &lt; 1e9) {
        return std::to_string(totalDistance / 1e6) + " trillion";
    } else {
        assert(false);  // presumably?
    }
}




Are you at all concerned that 1e3, a.k.a. 1000, is not "a million", and so on?



It is unclear to me whether totalDistance is supposed to be measured in kilometers, or meters, or what. (Megameters would make the math come out right, I suppose, but that just seems crazy.) I strongly recommend that any time you're dealing with measurements or other "unit-ful" data, you encode the expected units into the variable name, unless the expected units are already encoded in the variable's type. For example:

std::chrono::milliseconds timeout;  // excellent
int timeout_ms;  // excellent
int timeout;  // horrible

boost::units::kilometers totalDistance;  // excellent (hypothetically; this isn't actually how Boost.Units works)
int totalDistanceKm;  // excellent
int totalDistance;  // horrible