简体   繁体   中英

C++ Large numbers power of 10

New to C++ programming. Is there a way make the code better so that it does not have repeated code.

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

I am supposing you are not using totalDistance anymore, and you don't need an endl if you are already using '\\n'.

Easiest improvement:

if (totalDistance < pow(10, 3)) {
    outputDistance(totalDistance); 
}
else if (totalDistance < pow(10, 6)) {
    totalDistance = totalDistance / pow(10, 3);
    outputDistance(totalDistance); 
}
else if (totalDistance < pow(10, 9)) {
    totalDistance = totalDistance / pow(10, 6);
    outputDistance(totalDistance); 
}

private void outputDistance(const double totalDistance) {
cout << "\nTotal (approx) travel distance = " << totalDistance << " trillion km\n" << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM