별의 공부 블로그 🧑🏻‍💻
728x90
728x170

Here are some things that may help you improve your code.

Don't use std::endl if you don't really need it

The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid. I don't know that you've actually done that, but it's an alarmingly common thing for new C++ programmers to do.

Consider more descriptive variable names

From trying the code, I infer that totalDistance is apparently in millions of kilometers. It might be better to either reflect that in the variable name or to at least provide a comment near that variable to point out this essential fact.

Consider a data-centric approach

Rather than repeating things in code, a data structure might be more apppropriate:

void distprint(int totalDistance) { 
    constexpr struct { 
        int lolimit; 
        const char *name; 
    } 
    scales[]{ { 1'000, "million" }, 
              { 1'000'000, "billion" }, 
              { 1'000'000'000, "trillion" }, }; 
    for (const auto &scale : scales) { 
        if (totalDistance < scale.lolimit) { 
            std::cout << "\nTotal (approx) travel distance = " << totalDistance/(scale.lolimit/1'000) << ' ' << scale.name << " km \n"; 
            return; 
        } 
    } 
} 

Note that this actually uses the C++14 separator ' for numbers to make them easier to read. If you're stuck with only C++11, you can simply omit them.

Consider validating the input value

What should be printed if the number is negative? What if it's greater than 1000 trillion? At the moment, the first case would print as millions no matter the scale, and the latter wouldn't print anything at all. If that's not what you intend, it is wort looking more closely at how you've implemented this.

 


 

코딩을 하면서 도움이 될 만한 내용을 우연히 찾게 되어 올려본다.

 

내용 출처 : https://codereview.stackexchange.com/questions/145284/large-numbers-power-of-10

728x90
그리드형(광고전용)
⚠️AdBlock이 감지되었습니다. 원할한 페이지 표시를 위해 AdBlock을 꺼주세요.⚠️
starrykss
starrykss
별의 공부 블로그 🧑🏻‍💻


📖 Contents 📖