C ++编程新手。有没有办法使代码更好,以便它没有重复的代码。
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;
}
答案 0 :(得分:1)
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";
}
我假设您不再使用totalDistance,如果您已经在使用&#39; \ n&#39;
,则不需要endl。答案 1 :(得分:0)
最简单的改进:
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;
}